Do not 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, 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.) Similarly, if an object is referred to outside of its lifetime, the behavior is undefined. (See undefined behavior 9 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.
Noncompliant Code Example
This example from Brian Kernighan and Dennis Ritchie [Kernighan 1988] shows both the incorrect and correct techniques for freeing the memory associated with a linked list. In their incorrect solution, p
is freed before the p->next
is executed, so p->next
reads memory that has already been freed.
Code Block | ||||
---|---|---|---|---|
| ||||
#include <stdlib.h> struct node { int value; struct node *next; }; void free_list(struct node *head) { for (struct node *p = head; p != NULL; p = p->next) { free(p); } } |
Compliant Solution
Kernighan and Ritchie also show the correct solution. To correct this error, a reference to p->next
is stored in q
before freeing p
.
Code Block | ||||
---|---|---|---|---|
| ||||
#include <stdlib.h> struct node { int value; struct node *next; }; void free_list(struct node *head) { struct node *q; for (struct node *p = head; p != NULL; p = q) { q = p->next; free(p); } } |
Noncompliant Code Example
In this noncompliant code example, buff
is written to after it has been freed. These vulnerabilities can be easily exploited to run arbitrary code with the permissions of the vulnerable process and are seldom this obvious. Typically, allocations and frees are far removed, making it difficult to recognize and diagnose these problems.
Code Block | ||||
---|---|---|---|---|
| ||||
#include <stdlib.h> #include <string.h> enum { BUFFERSIZE = 32 }; int main(int argc, const char *argv[]) { char *buff = (char *)malloc(BUFFERSIZE); if (!buff) { /* Handle error */ } free(buff); if (argc > 1) { strncpy(buff, argv[1], BUFFERSIZE - 1); } return 0; } |
Compliant Solution
In this compliant solution, the memory is freed after its final use, and the pointer is zeroed in compliance with MEM01-C. Store a new value in pointers immediately after free():
Code Block | ||||
---|---|---|---|---|
| ||||
#include <stdlib.h> #include <string.h> enum { BUFFERSIZE = 32 }; int main(int argc, const char *argv[]) { char *buff = (char *)malloc(BUFFERSIZE); if (!buff) { /* Handle error */ } if (argc > 1){ strncpy(buff, argv[1], BUFFERSIZE - 1); } free(buff); buff = 0; return 0; } |
Noncompliant Code Example
In this noncompliant example (CVE-2009-1364) from libwmf
version 0.2.8.4, the return value of gdRealloc
(a simple wrapper around realloc
that reallocates space pointed to by im->clip->list
) is set to more
. However, the value of im->clip->list
is used directly afterwards in the code, and the C Standard specifies that if realloc
moves the area pointed to, then the original is freed. An attacker can then execute arbitrary code by forcing a reallocation (with a sufficient im->clip->count
) and accessing freed memory [xorl 2009].
Code Block | ||||
---|---|---|---|---|
| ||||
void gdClipSetAdd(gdImagePtr im,gdClipRectanglePtr rect) { gdClipRectanglePtr more; if (im->clip == 0) { /* ... */ } if (im->clip->count == im->clip->max) { more = gdRealloc (im->clip->list,(im->clip->max + 8) * sizeof (gdClipRectangle)); /* * If the realloc fails, then we have not lost the * im->clip->list value. */ if (more == 0) return; im->clip->max += 8; } im->clip->list[im->clip->count] = (*rect); im->clip->count++; |
Compliant Solution
The compliant solution simply reassigns im->clip->list
to the value of more
after the call to realloc
:
Code Block | ||||
---|---|---|---|---|
| ||||
void gdClipSetAdd(gdImagePtr im,gdClipRectanglePtr rect) { gdClipRectanglePtr more; if (im->clip == 0) { /* ... */ } if (im->clip->count == im->clip->max) { more = gdRealloc (im->clip->list,(im->clip->max + 8) * sizeof (gdClipRectangle)); if (more == 0) return; im->clip->max += 8; im->clip->list = more; } im->clip->list[im->clip->count] = (*rect); im->clip->count++; |
Noncompliant Code Example
In this example, an object is referred to outside of its lifetime:
Code Block | ||||
---|---|---|---|---|
| ||||
int *get_ptr(void) { int obj = 12; return &obj; } void func(void) { int *ptr = get_ptr(); *ptr = 42; } |
Compliant Solution
In this compliant solution, allocated storage is used instead of automatic storage for the pointer:
Code Block | ||||
---|---|---|---|---|
| ||||
#include <stdlib.h> int *get_ptr(void) { int *ptr = (int *)malloc(sizeof(int)); if (!ptr) { return 0; } *ptr = 12; return ptr; } void func(void) { int *ptr = get_ptr(); if (ptr) { *ptr = 42; free(ptr); ptr = 0; } } |
Risk Assessment
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 vulnerable process.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
MEM30-C | High | Likely | Medium | P18 | L1 |
Automated Detection
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
|
|
| |||||||
| 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 | |||||||
5.0 |
|
| |||||||
| UFM.DEREF.MIGHT |
| |||||||
| 51 D | Fully implemented | |||||||
|
|
|
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
CERT C Secure Coding Standard | MEM01-C. Store a new value in pointers immediately after free() |
CERT C++ Secure Coding Standard | MEM30-CPP. Do not access freed memory |
ISO/IEC TR 24772:2013 | Dangling References to Stack Frames [DCM] Dangling Reference to Heap [XYK] |
ISO/IEC TS 17961 | Accessing freed memory [accfree] |
MISRA C:2012 | Rule 18.6 (required) |
MITRE CWE | CWE-416, Use after free |
Bibliography
[Kernighan 1988] | Section 7.8.5, "Storage Management" |
[OWASP Freed Memory] | |
[Seacord 2013] | Chapter 4, "Dynamic Memory Management" |
[Viega 2005] | Section 5.2.19, "Using Freed Memory" |
[xorl 2009] | CVE-2009-1364: LibWMF Pointer Use after free() |