Skip to main content
GameDev.net gamedev.net
🔒 Locked

Dangling pointers

Started by Wicked Ewok Jan 22, 2004 at 1:08 AM 1 replies 500+ views
Original Post
Wicked Ewok
Wicked Ewok
I''m trying to NULL out dangling pointers when I delete an object. Smart pointers seem to only address garbage collection when you''re careless with your pointers and lose all link to your object... But when you have several pointers referencing an object, and you delete the object, it would be nice to have all the pointers referencing that object to now reference NULL. The first solution I did was to set the object flagged to delete, have the lists that reference it autoupdate and NULL out their pointers before deleting and then deleting the object in a deletion process at the end of an update loop. That sort of system is very inflexible and has many ways to cause problems on its own. I was thinking of keeping track of the pointers that were assigned a particular object, and upon deletion, in the object''s destructor, NULL out all those pointers. The problem with this is that if those pointers to pointers themselves are bad pointers, you''ll have yet another bad dangling pointer problem. Is there a way to detect bad pointers in runtime? Thanks -Marv
-=~''^''~=-.,Wicked,.-=~''^''~=-
Fruny
Fruny
If you have several pointers to an object, you should not delete that object until all those pointers are gone. On the other hand, you mlay use a scheme in which only some of those pointers are considered as ''owning'' the object. The others are ''weak pointers'' (e.g. boost::weak_ptr), which automatically get nulled when all the owning pointers are gone and the object gets deleted. And yes, that *does* involve smart pointers (e.g. boost::shared_ptr). Using smart poitners, losing all links to an object is not ''careless'', it''s how you know you don''t need it anymore - you don''t explicitely delete the object yourself.

That being said, there is no simple way of determining if a pointer is good or bad, without hacking into the memory allocation routines themselves.


“Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.” — Brian W. Kernighan (C programming language co-inventor)
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
Wicked Ewok
Wicked Ewok
ah ok, thanks. I understand why it would work in this sense, since you have two types of pointers to use. That helps a lot, thanks again.

-Marv
-=~''^''~=-.,Wicked,.-=~''^''~=-

Topic Locked

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

Sign in to reply to this topic.