Deleteing dynamic arrays

Hello every one I have a question that I am sure you have seen a million times but I am not wanting code. I am writing a dynamic array class for an assignment. The book wants an add entry function that creates a new dynamic array copies everything from the first into the second and adds the entry to the end of the new array, increments the size and deletes the old one. Well I kept getting a memory corruption error after the program printed out what it was suppose to and was ending.I commented out the delete statement in the function and it was gone. This drove me crazy for a while until I just got an idea and please correct me if i am wrong but what i think is happening is that the delete statement in the add entry function is deleting the old array and the programs ends and calls the destructor which again tries to delete what is already gone. If I am correct do I even need to add that delete statement if the destructor is being called anyway because if I comment out the delete in the destructor but leave in the statement in the function it runs fine and vise versa. I hope this rambling will make since to some of you. I will post a little of this to hopefully help with what I am trying ask. Thanks for your time.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
 template<class T>
DynamicTemplateArray<T>::~DynamicTemplateArray()
{
	delete [] _dynamicArray;
}

template<class T>
void DynamicTemplateArray<T>::addEntry(const T entry)
{
	int newSize = _size +1;
	T *newArray = new T[newSize];
		
	for(int i =0; i < _size; i++)
	{
		newArray[i] = _dynamicArray[i];
	}
	
	_dynamicArray = newArray;
	_dynamicArray[_size] = entry;
	_size++;
	
	delete [] newArray;
	
	
}
When you do:

_dynamicArray = newArray;

you are making _dynamicArray point to the same memory address as newArray. Then, when you do:

delete [] newArray;

you're deleting the array that both newArray and _dynamicArray are pointing to. At this point, you have lost the memory that you allocated on line 11.

When your destructor tries to delete _dynamicArray, it crashes, because you've already done it when you did delete [] newArray;
Thank you MikeyBoy.
You're welcome :)
Topic archived. No new replies allowed.