Pointer array deallocation issue - delete[]

I wrote this class which is supposed to help handle memory allocation/deallocation.

It errors in the deallocation routine.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
template <class T>
struct itemPList {
public:
	int count;
	T* items;

	itemPList() {
		count = 0;
		items = new T[0];
	};

	~itemPList() {
		for (int i = 0; i < count; i++) {
			delete[] items[i]; //errors here with _BLOCK_TYPE_IS_INVALID(pHead->nBlockUse)
		};
		delete[] items;
	};

	void addItem(T item) {
		addArrayElement<T>(items, item, count);
	};
};


I created an instance of this class using...

 
itemPList<sometype *> somelist;


I populated the array with...

 
somelist.addItem(new sometype())


Why do I get this memory error please? I can't figure it out.

Nice one...
items = new T[0];
Starting by creating an array of size zero does not have a good feel to it, and neither does writing your code so that the class responsible for deleting things is not the same one that created them, but that all aside, what does addArrayElement do? Are you expanding that array before you add things to it?

delete[] items[i];
You're now calling the array-delete operator on every individual element. No no no. Call the array-delete on things you made with the array-new operator. Each element was made with the new operator (new sometype()), so must be deleted with the delete operator (delete items[i];)
Last edited on
items is a pointer to an array of pointers.

EVERY element in the array is declared using new and needs to be disposed of when the array is disposed.

I appreciate it might seem strange, but theoretically... it should work. right?

addArrayElement works fine. If I do the delete[] loop manually (outside the template/class), the code works fine... it seems to only fail when it is inside the deconstructor...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

template <class T> void addArrayElement(T* &thearray, T theelement, basicCount &thecount) {
	T* ItemsTemp = new T[thecount + 1];

	for (basicLoop i = 0; i < thecount; i++) {
		ItemsTemp[i] = thearray[i];
	}

	ItemsTemp[thecount] = theelement;

	if (thecount != 0) {
		delete[] thearray;
	};
	thearray = ItemsTemp;
	thecount++;
};
Last edited on
You're now calling the array-delete operator on every individual element. No no no. Call the array-delete on things you made with the array-new operator. Each element was made with the new operator (new sometype()), so must be deleted with the delete operator (delete items[i];)


I am deleting only elements that were created with the new operator??
Wait. So I should do...


 
delete items[i];


...not...


 
delete[] items[i];



Sweet. I get ya. Will try...
Thanks. That fixed it. Nice one!
Topic archived. No new replies allowed.