Do I have to release heap memory?

Let's say I have a pointer like this:

int * meow = new int [25];

Then I create some other array:

int * bloop = new int [30];

Then stuff happens, and I make meow point to the new array:

meow = bloop;

So now meow points to the array of size 30. But what happens to the original stuff it was pointing at? Do I have to manually delete it, or does the heap memory automatically go back to the heap?

Thanks!
Last edited on
You need to delete[] it before you make the pointer point to something else, otherwise it's a memory leak.
Ok, that kind of made sense to me, I just thought that c++ might figure out that nothing is holding onto it and let it go. So I want to do:

delete [] meow;

and then

meow = bloop;

? Just to make sure, delete only deletes the heap memory the pointer is pointing at, not the pointer itself, right?
There are smart pointers that use reference counting and would know better but you have to explicitly use one of them.

Here's a link with more information (see boost::shared_ptr):
http://www.boost.org/doc/libs/1_43_0/libs/smart_ptr/smart_ptr.htm

Actually, if you're using a relatively new compiler it might have the TR1 headers available right out of the box.
Last edited on
Just to make sure, delete only deletes the heap memory the pointer is pointing at, not the pointer itself, right?

Yes. It leaves you with a dangling pointer.
Last edited on
Ok, so when memory is leaked, how far does that extend? Let's say I leak lots of memory, but my program finishes execution. Is that memory still leaked, will it slow down my OS? Or will my OS clean it up?
The OS will clean it up. But I suggest not getting into the habit of leaking memory.
Alright, thanks!
Topic archived. No new replies allowed.