how do i delete pointers safely

Started by
7 comments, last by wannabe H4x0r 21 years, 1 month ago
if i have for example a pointer to a pointer to a pointer, in say a linked list or a heap array of pointers and i would like to remove the structure altogether, can i just delete the top pointer and be done with or do i have to individually delete each one to prevent a memory leak?
Advertisement
Gotta delete 'em all. The simplest way to do this is have the node's destructor delete the next node.

[edited by - civguy on March 4, 2003 5:07:16 PM]
alright thanks, but another question:

when i define a pointer, do i have to set it to NULL each time a pointer is created?
You don''t have to, but it''s usually considered good practice to initialise all your pointers to 0 to avoid accidents.
quote:Original post by wannabe H4x0r
when i define a pointer, do i have to set it to NULL each time a pointer is created?


Is a good practice. There could come the time when you won''t know if the pointer you are trying to access has been already initialized. If you access this pointer without set it to null it will point to #CCCCCC or crap and will hang your proguie.
[size="2"]I like the Walrus best.
depends on what you mean by create. When you have a statement like:

int* a;

You should write

int* a = NULL; or int a* = 0;

because it''s not guarenteed to null when created.
what about an array of pointers? i would like to set each one to NULL on initialization of the array rather than run through a loop...
quote: it''s usually considered good practice to initialise all your pointers to 0 to avoid accidents.

A better practice is to initialize the pointer directly to the object it will point to, and 0 if it won''t point to any object. Usually variable declaration should be delayed until you''ll have something to put there. Linked lists are another thing though, since there it''s reasonable to have null pointers.
quote:what about an array of pointers? i would like to set each one to NULL on initialization of the array rather than run through a loop...
Use a vector.
quote:Original post by civguy Linked lists are another thing though, since there it''s reasonable to have null pointers.


There are lots of other cases where it''s reasonable to have null pointers.

This topic is closed to new replies.

Advertisement