Archived

This topic is now archived and is closed to further replies.

LordElectro

[C++] new[ ] with delete

Recommended Posts

LordElectro    122
We all know that: int *t; t = new[5]; delete t; is a bad thing to do. However, is this allowable? int *t; int i; t = new[5]; for( i=0; i<5; i++ ) delete &t; I have a situation where this sort of thing may happen, and I don''t want to just hope it''s correct...

Share this post


Link to post
Share on other sites
Sneftel    1788
No, it isn''t allowable. The memory manager does stuff in the background to keep track of allocation sizes, and this will screw with that.

Under what circumstances would you not know if you''re deleting an array, or a bunch of individual allocations that randomly ended up next to each other?


How appropriate. You fight like a cow.

Share this post


Link to post
Share on other sites
Stagz    196
I am not sure what you are trying to do here, but what you have there doesn't look quite right.

Try using this instead:


  
int **t;
int i;
int tmp;

// to create the array

t=new int*[5]
for(i=0; i<5; i++) t[i] = new int;

// to reference an item

tmp = *t[0];

// to delete a single item

delete t[0];

// to create a single item

t[0] = new int;

//then to delete all of them

for(i=0; i<5; i++) delete t[i];
delete [] t;



[edited by - stagz on March 19, 2003 10:07:41 PM]

Share this post


Link to post
Share on other sites
Sneftel    1788
quote:
Original post by Stagz
I am not sure what you are trying to do here, but what you have there doesn''t look quite right.


That''s because the forum took out his [ i ]. Yet another reason to use [ source ] tags.


How appropriate. You fight like a cow.

Share this post


Link to post
Share on other sites
LordElectro    122
quote:
Original post by Sneftel
No, it isn''t allowable. The memory manager does stuff in the background to keep track of allocation sizes, and this will screw with that.

Under what circumstances would you not know if you''re deleting an array, or a bunch of individual allocations that randomly ended up next to each other?



That''s what I suspected, thanks. What I was trying to do was allocate a whole block of objects that at a later time might not necessarily all be deleted at the same time (but would all be deleted before anymore objects of this type were allocated). Oh well, it just means lots of small allocations happening.

Share this post


Link to post
Share on other sites