Dynamic array resize function problems

Apr 22, 2014 at 7:40am
NOTE: I am aware that it would be easier to just use the STL Vector, however, for a programming class that I'm in, we are required to write our own dynamic array template class because our professor apparently enjoys making us reinvent the wheel.

Anyway, I made a resize function for my dynamic array template class that goes as follows. Note that the private member variables are T* arr, unsigned used, and unsigned cap.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
template <class T>
void darray<T>::resize(unsigned size)
{
	if (size > cap)
	{
		T* temp_arr = new T[size];

		for (int count = 0; count < cap; ++count)
			temp_arr[count] = arr[count];

		for (int count = cap; count < size; ++count)
			temp_arr[count] = T();

 		delete []arr;
		arr = temp_arr;
		cap = size;
		used = size;
	}

	if (size < cap)
	{
		used = size;
	}
}


Whenever I use this function to increase the size of the array, it will work the first time I need to use it, but after that, Visual Studios will trigger a breakpoint at line 14, and if I continue past the breaks, I eventually get _CrtIsValidHeapPointer(pUserData) assertion failure. What is causing this, and how can I fix it?
Apr 22, 2014 at 7:58am
One issue here with the correctness of the code. One should not copy cap elements to the newly allocated array. One should, instead, copy used elements.

I don't see anything here that would cause your problem. I suspect the offending code doesn't reside in this function.
Apr 22, 2014 at 8:52am
The only other thing that uses the private members of the the class in the code that I'm using to test is a a simple push member function that calls resize when used is > cap, so I'm not sure what it could be...
Apr 22, 2014 at 9:18am
I found the issue. My problem was that I was setting used = size, which defeats the point of the resize if I'm just going to need to need resize again after I use push_back.
Apr 22, 2014 at 5:57pm
I see. So the push_back probably used the used variable to write to a location beyond the bounds of the array.

The convention followed by std::vector is that the amount returned by size (analogous to your used member) after a resize is increased.
Topic archived. No new replies allowed.