Dangling pointer

   

Dangling pointers in programming are pointers whose objects have since been deleted or deallocated, without modifying the value of the pointer. In many languages (particularly the C programming language), deleting an object from memory does not alter any associated pointers. The pointer still points to the location in memory where the object or data was, even though the object or data has since been deleted and the memory may now used for other purposes. A pointer in such a situation is called a dangling pointer.

Using a dangling pointer under the assumption that the object it points to is still valid can cause unpredictable behaivor, including silent corruption of unrelated data and the crash of the offending program. To avoid bugs of this kind, one common programming technique is to set pointers to the null pointer once the storage they point to has been released. When the null pointer is dereferenced the program will immediately terminate — there is no potential for data corruption or unpredictable behavior. This makes the underlying programming mistake easier to find and resolve.

The following example code (in C++) shows a dangling pointer:

#include <iostream>
#include <string>  

using namespace std; // the string object is in the "std" namespace  

int main(void) {
   // create a pointer to a string object containing "This is a string."
   string *stringPointer = new string("This is a string.");
   // display the address of the string and its value
   cout << stringPointer << ": " << *stringPointer << endl;
   // the string has now been deleted; however, stringPointer
   // still points to the string's former location in memory
   delete stringPointer;
   // display the address (unchanged) and the new value; this will
   // likely crash the program or cause unpredictable behaivor
   cout << stringPointer << ": " << *stringPointer << endl;                                                         
   return 0;
}

Retrieved from "http://www.mywiseowl.com/articles/Dangling_pointer"

This page has been accessed 69 times. This page was last modified 13:30, 31 Oct 2004. All text is available under the terms of the GNU Free Documentation License (see Copyrights for details).