If this is your first visit, be sure to
check out the FAQ by clicking the
link above. You may have to register
before you can post: click the register link above to proceed. To start viewing messages,
select the forum that you want to visit from the selection below.

K, it might be obvious to anybody familiar with pointers and memory allocation, but I'll bet a few of you have done the same thing sometime or another! Please, post a solution and let me know how quick you figured it out! :D

I didn't test the code but I think your last loop shouldn't check
if (things [i].deally != 0)

Simply use
delete [] things [i].deally;

in a loop that has thingscount iterations. Deleting a NULL pointer is harmless and safe, and besides, I would simply move the allocation and deallocation stuff to a constructor and destructor inside Thing. It's so much simpler!

No matter.
As for the program- it would be easier/cleaner to use a constructor/destructor to alloc/delete the data, but the idea was to code up a quick example demonstrating a major flaw I came across in a much larger program (without posting not-working pieces of the larger program here).

And for those who are to lazy (or just don't have the time to figure it out), here's where the memory leak happens.

The leak occurs when assigning things [x] to things [thingCount]. Normally, this would work fine. All the elements in things [x] are set to the values in things [thingCount]. BUT! there's a pointer in them thar elements!!! meaning, the pointer in things [x] is overwritten and LOST! Leak!!! This is kinda a harmless leak, since the data lost was to be deleted anyway (and not accessed again). The larger problem is the next few lines, where thing [thingCount] is deleted. Since the pointer here is the same address as the one in things [x], the array in things [x] is deleted! And the program may expect to access (read and write) data to that array! It's not an easy error to catch when you've got to go through hundreds of lines of code...

The solution: Realizing that the pointer will be overwritten anyway, delete it and prevent that part of the leak. Then, do not delete the array in the last element. Instead, set the pointer to null and "deallysize" to zero. Setting the pointer to null without deleting the array is very wrong by any tutorial standards I've come across, but since the array exists twice, it's safe to remove the reference to it once.

This way, not only is the memory management completely automatic, you don't need to track the size of the array manually. Additionally, copying a Thing object is perfectly safe because vector defines a copy ctor and assignment opeartor. I think that your example is a compelling argument in favor of vector and STL in general.