Skip to main content
gamedev.net
🔒 Locked

how do i delete pointers safely

Started by wannabe H4x0r 7 replies 400+ views
Original Post
wannabe H4x0r
wannabe H4x0r
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?
civguy
civguy
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]
wannabe H4x0r
wannabe H4x0r
alright thanks, but another question:

when i define a pointer, do i have to set it to NULL each time a pointer is created?
owl
owl
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.
Mulligan
Mulligan
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.
wannabe H4x0r
wannabe H4x0r
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...
civguy
civguy
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.
Nacht
Nacht
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.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.