SatView: Pointer Perfect, part 4 - Dangling Pointers
(Page 3 of 5 )
A dangling pointer is a pointer that once was pointing to the right object, but was referenced after the object it pointed at was freed. The easiest way to demonstrate this is:
int *ptr = new int(2);
delete ptr;
*ptr = 3; // oops accessing dangling pointer!
Well nobody is going to make a mistake as obvious as this one (at least not that often), but unfortunately mistakes sometimes only turn out to be obvious after you’ve made them! The next piece of code should be fairly easy to recognize as being wrong too:
std::list<int>* foo() {
std::list<int> result;
/* perform operations to fill result list here */
return &result;
}
The idea behind this function might be clear, but it was clearly forgotten that the result is constructed on the stack. This means that the memory it occupies is freed when we leave the function, which leaves the pointer we returned dangling in the wild!
A nasty way to create dangling pointers is to forget that the compiler implicitly creates a copy constructor and assignment operator for your class when you don’t declare them. This does become a problem when you use pointers as member variables, since the compiler only facilitates in bitwise copiers for you, which create shallow copies of your class. And a shallow copy of your class has copied the pointer address instead of the memory at which it is pointing! This can lead to all sorts of trouble.
You either have to hide the copy constructor and assignment operator by making them private and thus making your class non-copyable, or define them to make a copy of the memory the pointer members are holding (creating a deep copy of your class).
Let's demonstrate a shallow copy.
class Shallow {
public:
explicit Shallow(int value) : m_pInt(new int(value)) {}
~Shallow() { try { delete m_pInt; } catch (…) {} }
int *m_pInt;
};
void foo(Shallow param) {
/* perform some operations here */
}
void test() {
Shallow shallow(2);
foo(shallow);
(void)printf(“shallow.m_pInt has value 0x%x.\n”, *shallow.m_pInt);
}
Running the code above in debug mode will yield the following output (or something similar):
pointer shallow.m_pInt is 0x002F0930.
pointer param.m_pint is 0x002F0930.
shallow.m_pInt has value 0xdddddddd.
and a “Debug Assertion Failed!” when using Microsoft Visual Studio .Net 2003. It captured the fact that shallow was trying to delete its m_pInt which already was deleted by param when foo() exited! Because shallow was passed by value to foo() a shallow copy was constructed for it and the resulting (shallow) param inherited the pointer which it correctly freed upon leaving the function.
Basically the error demonstrated in the code above looks a lot like what could happen when you use the std::auto_ptr. Maybe this provides a good explanation as to why the Standards Committee has chosen to make the auto_ptr behave the way it does?
Next: Performance Hit When Initializng >>
More C# Articles
More By J. Nakamura