Dangling pointer

If the program writes to memory referenced by a dangling pointer, a silent corruption of unrelated data may result, leading to subtle bugs that can be extremely difficult to find.

If the program has sufficient privileges to allow it to overwrite the bookkeeping data used by the kernel's memory allocator, the corruption can cause system instabilities.

Antoni Kreczmar [pl] (1945–1996) has created a complete object management system which is free of dangling reference phenomenon.

[6] In C, the simplest technique is to implement an alternative version of the free() (or alike) function which guarantees the reset of the pointer.

The alternative version can be used even to guarantee the validity of an empty pointer before calling malloc(): These uses can be masked through #define directives to construct useful macros (a common one being #define XFREE(ptr) safefree((void **)&(ptr))), creating something like a metalanguage or can be embedded into a tool library apart.

This approach completely eliminates dangling pointer errors by disabling frees, and reclaiming objects by garbage collection.

In the language Rust, the type system has been extended to include also the variables lifetimes and resource acquisition is initialization.

Unless one disables the features of the language, dangling pointers will be caught at compile time and reported as programming errors.

When the null pointer is dereferenced (in most languages) the program will immediately terminate—there is no potential for data corruption or unpredictable behavior.

This usually prevents the data from being reused by making it useless and also very prominent (the pattern serves to show the programmer that the memory has already been freed).

Another strategy, when suspecting a small set of classes, is to temporarily make all their member functions virtual: after the class instance has been destructed/freed, its pointer to the Virtual Method Table is set to NULL, and any call to a member function will crash the program and it will show the guilty code in the debugger.

Dangling pointer