The bane of Dangling Pointers

Ian Monroe ian.monroe at gmail.com
Mon Dec 21 13:53:49 CET 2009


On Mon, Dec 21, 2009 at 3:14 AM, Mark Kretschmann <kretschmann at kde.org> wrote:
> 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)

QSharedPointers can be fairly dangerous if not used correctly. Whereas
QPointer is to solve the dangling pointer issue, and are pretty much
"free" for any QObject (they just connect to existing signals),
QSharedPointers is for memory management. So you have to be mindful
when using QShared*Pointers/KSharedPtr (basically you must ensure that
the ref-counting is happening correctly by not passing around the bare
pointer too much). And I would say its totally overkill if you're only
worried about dangling pointers.

Also QSharedPointers do their referencing counting inside the pointer
object. This is inferior to QSharedDataPointer and KSharedPtr which
hold the reference counter inside the object itself (so you can pass
the bare pointer, make a QSharedDataPointer or KSharedPtr from it and
the counting works just fine). So I'd say to always use KSharedPtr,
unless you are holding a pointer to an object defined in a library
that you can't derive from QSharedData.

Ian


More information about the Amarok-devel mailing list