Accessing memory once it is freed may corrupt the data structures used to manage the heap. When a chuck memory is freed using free, the underlying structures that manage the block of memory to be freed manipulate that chunk to place back in to the pool of memory available for allocation. References to memory that has been deallocated are typically referred to as dangling pointers. Accessing a dangling pointer can lead to security vulnerabilities, for instance VU#390044.
When memory is freed its contents may remain intact and accessible. This is 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 to be valid. However, this can change unexpectedly leading to unintended program behavior.
...
Non-compliant Code Example 1
This example Kerrington from Kerrighan 88 shows items being deleted from a linked list. However, Because p
is freed before the p->next
is executed. Thus, when p->next
is executed, p will refer to freed memory reads memory that has already been freed.
Code Block |
---|
for(p = head; p != NULL; p= p->next) |
...
Code Block |
---|
for (p = head; p != NULL; p= p->q) { q = p->next; free(p); } |
Consequences
Reading memory that has already been freed can lead to abnormal program termination and denial-of-service attacks.
Writing memory that has already been freed can lead to the execution of arbitrary code with the permissions of the vulnerabile process.
References
- ISO/IEC 9899-1999 Section 7.20.3.2 The free function
- Seacord 05 Chapter 4 Dynamic Memory Management
- Kerrighan 88 Section 7.8.5 Storage Management