-
new and delete operators
int *p = new int[2];
delete [] p;
The above sort of code is giving me major hassle! I'm using a 2d array of pointers and can't seem to free up the memory space that it is occupying when I delete it.
The pointer is set to NULL all right, but the data it used to point to is still there. I discovered this when I put another pointer pointing to the same data:
int *q = p;
After deleting p, q still points to the two integers in memory.
This is really frustrating as it seems to have loads of implications. What if I had a linked list of 5000 records and decided to delete it? Would the memory ever be freed up?! Please help!
I'm programming in Emacs,Linux
Thanks
-
> I'm using a 2d array of pointers
Well how did you use new to create the 2D array then?
> but the data it used to point to is still there.
Creating aliases for memory which has been deleted is a known cause of all sorts of problems.
> After deleting p, q still points to the two integers in memory.
Memory doesn't go anywhere when you delete it, only the official reference to that memory.
But that doesn't mean you can read it, because at any moment, it could get re-used.
-
Oh I see! Will having a second pointer keeping track of this value in memory after the first pointer (p) is deleted, prevent the data being overwritten in memory?
I have a function which returns an array of 2pointers.
Theis function is called three times, storing these reurned pointers in another pointer array.
That's great! Thanks for the help