Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

Dangling pointer

From Wikipedia, the free encyclopedia
Pointer that does not point to a valid object
Dangling pointer

Dangling pointers andwild pointers incomputer programming arepointers that do not point to a valid object of the appropriate type. These are special cases ofmemory safety violations. More generally,dangling references andwild references arereferences that do not resolve to a valid destination.

Dangling pointers arise duringobject destruction, when an object that is pointed to by a given pointer is deleted or deallocated, without modifying the value of that said pointer, so that the pointer still points to the memory location of the deallocated memory. The system may reallocate the previously freed memory, and if the program thendereferences the (now) dangling pointer,unpredictable behavior may result, as the memory may now contain completely different data. If the program writes to memory referenced by a dangling pointer, a silent corruption of unrelated data may result, leading to subtlebugs that can be extremely difficult to find. If the memory has been reallocated to another process, then attempting to dereference the dangling pointer can causesegmentation faults (UNIX, Linux) orgeneral protection faults (Windows). 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. Inobject-oriented languages withgarbage collection, dangling references are prevented by only destroying objects that are unreachable, meaning they do not have any incoming pointers; this is ensured either by tracing orreference counting. However, afinalizer may create new references to an object, requiringobject resurrection to prevent a dangling reference.

Wild pointers, also called uninitialized pointers, arise when a pointer is used prior to initialization to some known state, which is possible in some programming languages. They show the same erratic behavior as dangling pointers, though they are less likely to stay undetected because many compilers will raise a warning at compile time if declared variables are accessed before being initialized.[1]

Cause of dangling pointers

[edit]

In many languages (e.g., theC programming language) deleting an object from memory explicitly or by destroying thestack frame on return does not alter associated pointers. The pointer still points to the same location in memory even though that location may now be used for other purposes.

A straightforward example is shown below:

{char*dp=NULL;// ...{charc;dp=&c;}// c falls out of scope// dp is now a dangling pointer}

If the operating system is able to detect run-time references tonull pointers, a solution to the above is to assign 0 (null) to dp immediately before the inner block is exited. Another solution would be to somehow guarantee dp is not used again without further initialization.

Another frequent source of dangling pointers is a jumbled combination ofmalloc() andfree() library calls: a pointer becomes dangling when the block of memory it points to is freed. As with the previous example one way to avoid this is to make sure to reset the pointer to null after freeing its reference—as demonstrated below.

#include<stdlib.h>voidfunc(){char*dp=(char*)malloc(sizeof(char)*10);// ...free(dp);// dp now becomes a dangling pointerdp=NULL;// dp is no longer dangling// ...}

An all too common misstep is returning addresses of a stack-allocated local variable: once a called function returns, the space for these variables gets deallocated and technically they have "garbage values".

int*func(void){intnum=1234;// ...return&num;}

Attempts to read from the pointer may still return the correct value (1234) for a while after callingfunc, but any functions called thereafter may overwrite the stack storage allocated fornum with other values and the pointer would no longer work correctly. If a pointer tonum must be returned,num must have scope beyond the function—it might be declared asstatic.

Manual deallocation without dangling reference

[edit]

Antoni Kreczmar [pl] (1945–1996) has created a complete object management system which is free of dangling reference phenomenon.[2] A similar approach was proposed by Fisher and LeBlanc[3] under the nameLocks-and-keys.

Cause of wild pointers

[edit]

Wild pointers are created by omitting necessary initialization prior to first use. Thus, strictly speaking, every pointer in programming languages which do not enforce initialization begins as a wild pointer.

This most often occurs due to jumping over the initialization, not by omitting it. Most compilers are able to warn about this.

intf(inti){char*dp;// dp is a wild pointerstaticchar*scp;/* scp is not a wild pointer:                        * static variables are initialized to 0                        * at start and retain their values from                        * the last call afterwards.                        * Using this feature may be considered bad                        * style if not commented */}

Security holes involving dangling pointers

[edit]

Likebuffer-overflow bugs, dangling/wild pointer bugs frequently become security holes. For example, if the pointer is used to make avirtual function call, a different address (possibly pointing at exploit code) may be called due to thevtable pointer being overwritten. Alternatively, if the pointer is used for writing to memory, some other data structure may be corrupted. Even if the memory is only read once the pointer becomes dangling, it can lead to information leaks (if interesting data is put in the next structure allocated there) or toprivilege escalation (if the now-invalid memory is used in security checks). When a dangling pointer is used after it has been freed without allocating a new chunk of memory to it, this becomes known as a "use after free" vulnerability.[4] For example,CVE-2014-1776 is a use-after-free vulnerability in Microsoft Internet Explorer 6 through 11[5] that was used byzero-day attacks by anadvanced persistent threat.[6]

Avoiding dangling pointer errors

[edit]

In C, the simplest technique is to implement an alternative version of thefree() (or alike) function which guarantees the reset of the pointer. However, this technique will not clear other pointer variables which may contain a copy of the pointer.

#include<assert.h>#include<stdlib.h>// Safe version of free()staticvoidsafeFree(void**pp){// in debug mode, abort if pp is NULLassert(pp);// free(NULL) works properly, so no check is required besides the assert in debug modefree(*pp);// deallocate chunk, note that free(NULL) is valid*pp=NULL;// reset original pointer}intf(inti){char*p=NULL;char*p2;p=(char*)malloc(1000);// get a chunkp2=p;// copy the pointer// use the chunk heresafeFree((void**)&p);// safety freeing; does not affect p2 variablesafeFree((void**)&p);// this second call won't fail as p is reset to NULLcharc=*p2;// p2 is still a dangling pointer, so this is undefined behavior.returni+c;}

The alternative version can be used even to guarantee the validity of an empty pointer before callingmalloc():

safeFree(&p);// I'm not sure if chunk has been released */p=(char*)malloc(1000);// allocate now

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. In every case, programmers using this technique should use the safe versions in every instance wherefree() would be used; failing in doing so leads again to the problem. Also, this solution is limited to the scope of a single program or project, and should be properly documented.

Among more structured solutions, a popular technique to avoid dangling pointers in C++ is to usesmart pointers. A smart pointer typically usesreference counting to reclaim objects. Some other techniques include thetombstones method and thelocks-and-keys method.[3]

Another approach is to use theBoehm garbage collector, a conservativegarbage collector that replaces standard memory allocation functions in C andC++ with a garbage collector. This approach completely eliminates dangling pointer errors by disabling frees, and reclaiming objects by garbage collection.

Another approach is to use a system such asCHERI, which stores pointers with additional metadata which may prevent invalid accesses by including lifetime information in pointers. CHERI typically requires support in the CPU to conduct these additional checks.

In languages like Java, dangling pointers cannot occur because there is no mechanism to explicitly deallocate memory. Rather, the garbage collector may deallocate memory, but only when the object is no longer reachable from any references.

In the languageRust, thetype system has been extended to include also the variables lifetimes andresource acquisition is initialization. Unless one disables the features of the language, dangling pointers will be caught at compile time and reported as programming errors.

Dangling pointer detection

[edit]

To expose dangling pointer errors, one common programming technique is to set pointers to thenull pointer or to an invalid address once the storage they point to has been released. 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 makes the underlying programming mistake easier to find and resolve. This technique does not help when there are multiple copies of the pointer.

Some debuggers will automatically overwrite and destroy data that has been freed, usually with a specific pattern, such as0xDEADBEEF (Microsoft's Visual C/C++ debugger, for example, uses0xCC,0xCD or0xDD depending on what has been freed[7]). 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).

Tools such asPolyspace,TotalView,Valgrind, Mudflap,[8]AddressSanitizer, or tools based onLLVM[9] can also be used to detect uses of dangling pointers.

Other tools (SoftBound,Insure++, andCheckPointer) instrument the source code to collect and track legitimate values for pointers ("metadata") and check each pointer access against the metadata for validity.

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

TheARM64 memory tagging extension (MTE) - disabled by default on Linux systems, but can be enabled onAndroid 16 - triggers asegmentation fault when it detects use-after-free andbuffer overflow.[10][11]

See also

[edit]

References

[edit]
  1. ^"Warning Options - Using the GNU Compiler Collection (GCC)".
  2. ^Gianna Cioni, Antoni Kreczmar,Programmed deallocation without dangling reference,Information Processing Letters, v. 18,1984, pp. 179–185
  3. ^abC. N. Fisher, R. J. Leblanc,The implementation of run-time diagnostics in Pascal,IEEE Transactions on Software Engineering, 6(4):313–319, 1980.
  4. ^Dalci, Eric; anonymous author; CWE Content Team (May 11, 2012)."CWE-416: Use After Free".Common Weakness Enumeration.Mitre Corporation. RetrievedApril 28, 2014.{{cite web}}:|author2= has generic name (help)
  5. ^"CVE-2014-1776".Common Vulnerabilities and Exposures (CVE). 2014-01-29. Archived fromthe original on 2017-04-30. Retrieved2017-05-16.
  6. ^Chen, Xiaobo; Caselden, Dan; Scott, Mike (April 26, 2014)."New Zero-Day Exploit targeting Internet Explorer Versions 9 through 11 Identified in Targeted Attacks".FireEye Blog.FireEye. RetrievedApril 28, 2014.[permanent dead link]
  7. ^Visual C++ 6.0 memory-fill patterns
  8. ^Mudflap Pointer Debugging
  9. ^Dhurjati, D. and Adve, V.Efficiently Detecting All Dangling Pointer Uses in Production Servers
  10. ^"Arm memory tagging extension".Android Open Source Project. Retrieved2025-06-11.
  11. ^Goodin, Dan (2025-05-13)."Google introduces Advanced Protection mode for its most at-risk Android users".Ars Technica. Retrieved2025-06-11.
Hardware
Virtual memory
Segmentation
Allocator
Manual means
Garbage
collection
Safety
Issues
Other
Retrieved from "https://en.wikipedia.org/w/index.php?title=Dangling_pointer&oldid=1318923409"
Categories:
Hidden categories:

[8]ページ先頭

©2009-2026 Movatter.jp