C Board  

Go Back   C Board > Platform Specific Boards > Linux Programming

Reply
 
LinkBack Thread Tools Display Modes
Old 10-12-2001, 12:36 PM   #1
Registered User
 
Join Date: Aug 2001
Posts: 4
Exclamation 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
Taidhger is offline   Reply With Quote
Old 10-12-2001, 12:44 PM   #2
and the hat of Jobseeking
 
Salem's Avatar
 
Join Date: Aug 2001
Location: The edge of the known universe
Posts: 21,693
> 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.
__________________
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.

Salem is offline   Reply With Quote
Old 10-12-2001, 12:54 PM   #3
Registered User
 
Join Date: Aug 2001
Posts: 4
Talking

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
Taidhger is offline   Reply With Quote
Reply

Thread Tools
Display Modes

Forum Jump


All times are GMT -6. The time now is 05:31 PM.


Powered by vBulletin® Version 3.8.1
Copyright ©2000 - 2010, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.3.2

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22