The bane of Dangling Pointers

Mark Kretschmann kretschmann at kde.org
Mon Dec 21 10:14:04 CET 2009


Hey all,

recently I have been thinking a lot about how we can fix our issues
with dangling pointers. First of all, if you don't know the term,
please see here:


http://en.wikipedia.org/wiki/Dangling_pointer

In short: It's a pointer that is pointing to an invalid object (in
most cases, the object was destroyed). If correctly handled, the
pointer should be set to 0 in this case. However, it's very easy to
miss this and forget setting it to 0. So, what we now have is a
pointer containing a random memory address of garbage. When you access
it, the behavior is undetermined. Most of the time, the program will
crash with a weird backtrace that is hard to debug.

Because these issues are so hard to debug, it's better not to make
such errors in the first place. And here's where "Smart Pointers" come
into play:


http://en.wikipedia.org/wiki/Smart_pointer

A Smart Pointer will automatically set the pointer to 0, if the object
it points to is destroyed. This makes it very easy to check for 0, and
this prevents a great deal of bugs. Does it have downsides? Yes, there
is some memory and performance overhead. However, in most cases this
tiny overhead is more than worth it, compared to the time you spend
with debugging such things. So please consider using Smart Pointers
more often, and if you are unsure if the Smart Pointer is needed in a
particular case, then just use it. "Better safe than sorry" applies
here.


Here are two classes that you can use with Qt 4.5:

* http://doc.trolltech.com/4.5/qsharedpointer.html
(Reference counting, thread-safe, works with any object)

* http://doc.trolltech.com/4.5/qpointer.html
(Not reference-counting, not thread-safe, only works with QObjects)

PS:
Here are two examples of recent dangling pointer issues:

http://gitorious.org/amarok/amarok/commit/f2e35485f3238163b3fae0fb3bcf3a14c407b1b4
http://gitorious.org/amarok/amarok/commit/acf150893523a4c1693abb2ccae32f91140cb01d


Happy Hackmas to all of you ;)
Mark.

-- 
Mark Kretschmann
Amarok Developer
Fellow of the Free Software Foundation Europe
www.kde.org - amarok.kde.org - www.fsfe.org


More information about the Amarok-devel mailing list