Do no evaluate any pointers into freed memory after an allocated block of dynamic storage has been deallocated by a memory management function, including dereferencing or acting as an operand of an arithmetic operation, type casting, or using the pointer as the right-hand side of an assignment.
According to the C standard [ISO/IEC 9899:2011], the behavior of a program that uses the value of a pointer that refers to space deallocated by a call to the free()
or realloc()
function is undefined. (See undefined behavior 177 of Annex J.)
Reading a pointer to deallocated memory is undefined because the pointer value is indeterminate and can have a trap representation. In the latter case, doing so may cause a hardware trap.
Accessing memory once it is freed may corrupt the data structures used to manage the heap. References to memory that has been deallocated are referred to as dangling pointers. Accessing a dangling pointer can result in exploitable vulnerabilities.
When memory is freed, its contents may remain intact and accessible because it is at the memory manager's discretion when to reallocate or recycle the freed chunk. The data at the freed location may appear valid. However, this can change unexpectedly, leading to unintended program behavior. As a result, it is necessary to guarantee that memory is not written to or read from once it is freed.
...
This example from Kernighan and Ritchie [Kernighan 1988] shows both the incorrect and correct techniques for deleting items from a linked list. The incorrect solution, clearly marked as wrong in the book, is bad because p
is freed before the p->next
is executed, so p->next
reads memory that has already been freed.
...
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
| 51 D | Fully implemented. | |||||||
Fortify SCA | V. 5.0 |
|
| ||||||
Splint |
|
|
| ||||||
Compass/ROSE |
|
|
| ||||||
| USE_AFTER_FREE | Can detect the specific instances where memory is deallocated more than once or read/written to the target of a freed pointer. | |||||||
| UFM.DEREF.MIGHT |
|
...
ISO/IEC TR 17961 (Draft) Accessing freed memory [accfree]
ISO/IEC TR 24772 "DCM Dangling references to stack frames" and "XYK Dangling reference to heap"
MISRA Rule 17.6
MITRE CWE: CWE-416, "Use after free"
Bibliography
[Kernighan 1988] Section 7.8.5, "Storage management"
[OWASP Freed Memory]
[Seacord 2005a] Chapter 4, "Dynamic Memory Management"
[Viega 2005] Section 5.2.19, "Using freed memory"
[xorl 2009] CVE-2009-1364: LibWMF Pointer Use after free()
...