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 be 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 behavior. This is because the program may not terminate as soon as the dangling pointer is used: the data referenced by the dangling pointer may not immediately be reused for other purposes. The use of dangling pointers can also result in the silent corruption of unrelated data. 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. Some other techniques include the tombstone (programming)s method and the locks-and-keys method.
The following example code (in C plus plus) shows a dangling pointer:
#include #include 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|
|