Jun 9, 2010 at 8:55pm UTC
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 Jun 9, 2010 at 8:56pm UTC
Jun 9, 2010 at 8:59pm UTC
You need to delete []
it before you make the pointer point to something else, otherwise it's a memory leak.
Jun 9, 2010 at 9:09pm UTC
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?
Jun 9, 2010 at 9:12pm UTC
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 Jun 9, 2010 at 9:13pm UTC
Jun 9, 2010 at 9:17pm UTC
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 Jun 9, 2010 at 9:17pm UTC
Jun 9, 2010 at 9:35pm UTC
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?
Jun 9, 2010 at 9:41pm UTC
The OS will clean it up. But I suggest not getting into the habit of leaking memory.