Before the lifetime of the last pointer that stores the return value of a call to a standard memory allocation function has ended, it must be matched by a call to free()
with that pointer value.
Noncompliant Code Example
In this noncompliant example, the object allocated by the call to malloc()
is not freed before the end of the lifetime of the last pointer text_buffer
referring to the object
As noted in undefined behavior 179 of Annex J of the C Standard [ISO/IEC 9899:2011], the behavior a program is undefined when
the pointer argument to the
free
orrealloc
function does not match a pointer earlier returned by a memory management function, or the space has been deallocated by a call tofree
orrealloc
.
Freeing memory multiple times has similar consequences to accessing memory after it is freed. (See MEM30-C. Do not access freed memory.) First, 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 can cause a hardware trap. When reading a freed pointer doesn't cause a trap, the underlying data structures that manage the heap can become corrupted in a way that can introduce security vulnerabilities into a program. These types of issues are called double-free vulnerabilities. In practice, double-free vulnerabilities can be exploited to execute arbitrary code. One example of this is VU#623332, which describes a double-free vulnerability in the MIT Kerberos 5 function krb5_recvauth().
To eliminate double-free vulnerabilities, it is necessary to guarantee that dynamic memory is freed exactly one time. Programmers should be wary when freeing memory in a loop or conditional statement; if coded incorrectly, these constructs can lead to double-free vulnerabilities. It is also a common error to misuse the realloc()
function in a manner that results in double-free vulnerabilities. (See MEM04-C. Do not perform zero-length allocations.)
Noncompliant Code Example (malloc()
)
In this noncompliant code example, the memory referred to by x
may be freed twice: once if error_condition
is true and again at the end of the code:
Code Block | ||||
---|---|---|---|---|
| ||||
int f(size_t n) { int error_condition = 0; int *x = (int*)malloc(n * sizeof(int)); if (x == NULL) return -1; /* Use x and set error_condition on error. */ if (error_condition == 1#include <stdlib.h> enum { BUFFER_SIZE = 32 }; int f(void) { char *text_buffer = (char *)malloc(BUFFER_SIZE); if (text_buffer == NULL) { /* Handle error condition*/ free(x)return -1; } /* ... */ free(x); return error_condition0; } |
Compliant Solution
...
In this compliant solution, the free a referenced by x
is only freed once. This is accomplished by eliminating the call to pointer is deallocated with a call to free()
when error_condition
is set:
Code Block | ||||
---|---|---|---|---|
| ||||
int f(size_t n) { int error_condition = 0; if (n > SIZE_MAX / sizeof(int))#include <stdlib.h> enum { BUFFER_SIZE = 32 }; int f(void) { errno = EOVERFLOW; return -1; } int *xchar *text_buffer = (intchar *)malloc(n * sizeof(int)BUFFER_SIZE); if (xtext_buffer == NULL) { /* Report allocation failure to caller. */ return -1; } /* Use x and set error_condition on error. */ if (error_condition != 0) { /* Handle error condition and proceed. */ } free(x); free(text_buffer); return error_condition0; } |
Note that this solution checks for numeric overflow. (See INT32-C. Ensure that operations on signed integers do not result in overflow.)
Noncompliant Code Example (realloc()
)
Exceptions
MEM31-C-EX1: Allocated memory does not need to be freed if it is assigned to a pointer whose lifetime includes program termination. The following code example illustrates a pointer that stores the return value from malloc()
in a static
variableThe memory referenced by p
may be freed twice in this noncompliant code example:
Code Block | ||||
---|---|---|---|---|
| ||||
/* p is a pointer to dynamically allocated memory */ p2 = realloc(p, size); if (p2 == NULL#include <stdlib.h> enum { BUFFER_SIZE = 32 }; int f(void) { static free(p);char /*text_buffer p= mayNULL; be indeterminate whenif (sizetext_buffer == 0NULL) */ return; } |
Section 7.22.3 of the C Standard [ISO/IEC 9899:2011] states:
If the size of the space requested is zero, the behavior is implementation-defined: either a null pointer is returned, or the behavior is as if the size were some nonzero value, except that the returned pointer shall not be used to access an object.
And Section 7.22.3.5 states:
If memory for the new object cannot be allocated, the old object is not deallocated and its value is unchanged.
If realloc()
is called with size
equal to 0, then if a null pointer is returned, the old value should be unchanged. However, there are some common but nonconforming implementations that free the pointer, including the following:
- Glibc (GNU/Linux)
- AIX
- HP-UX
- Solaris
- OSF/1
In nonconforming implementations, calling free
on the original pointer might result in a double-free vulnerability. However, not calling free
on the original pointer might result in a memory leak.
Compliant Code Example (realloc()
)
In this compliant solution, allocations of zero bytes are prevented, ensuring that p
is freed exactly once:
Code Block | ||||
---|---|---|---|---|
| ||||
/* p is a pointer to dynamically allocated memory */ if (size) { p2 = realloc(p, size); if (p2{ text_buffer = (char *)malloc(BUFFER_SIZE); if (text_buffer == NULL) { free(p); return return-1; } } else { free(p); } return 0; } |
...
MEM31-EX1: Some library implementations accept and ignore a deallocation of already-free memory. If all libraries used by a project have been validated as having this behavior, then this rule can be ignored.
Risk Assessment
Freeing Failing to free memory multiple times can result in an attacker executing arbitrary code with the permissions of the vulnerable processthe exhaustion of system memory resources, which can lead to a denial-of-service attack.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
MEM31-C |
Medium |
Probable |
Medium |
P8 |
L2 |
Automated Detection
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
Astrée |
| Supported, but no explicit checker | |||||||
Axivion Bauhaus Suite |
| CertC-MEM31 | Can detect dynamically allocated resources that are not freed | ||||||
CodeSonar |
| ALLOC.LEAK | Leak | ||||||
Compass/ROSE | |||||||||
| RESOURCE_LEAK |
ALLOC_ |
FREE_ |
MISMATCH | Finds resource leaks from variables that go out of scope while owning a resource |
Can find the instances where a freed memory is freed again. Coverity Prevent cannot discover all violations of this rule, so further verification is necessary
Cppcheck |
| memleak leakReturnValNotUsed leakUnsafeArgAlloc memleakOnRealloc | Doesn't use return value of memory allocation function | ||||||
Cppcheck Premium |
| memleak leakReturnValNotUsed leakUnsafeArgAlloc memleakOnRealloc | Doesn't use return value of memory allocation function | ||||||
Helix QAC |
| DF2706, DF2707, DF2708 C++3337, C++3338 |
Fortify SCA
5.0
Double Free
Klocwork |
|
UFM
CL.FFM.ASSIGN CL.FFM |
.COPY CL.SHALLOW.ASSIGN CL.SHALLOW.COPY FMM.MIGHT FMM.MUST | |||||||
LDRA tool suite |
|
484 S
50 D | Partially implemented | ||||||||
Parasoft C/C++test |
| CERT_C-MEM31-a | Ensure resources are freed | ||||||
Parasoft Insure++ | Runtime analysis | ||||||||
PC-lint Plus |
| 429 | Fully supported | ||||||
Polyspace Bug Finder |
| CERT C: Rule MEM31-C | Checks for memory leak (rule fully covered) | ||||||
PVS-Studio |
| V773 | |||||||
SonarQube C/C++ Plugin |
| S3584 | |||||||
Splint |
|
TrustInSoft Analyzer |
| malloc | Exhaustively verified. |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
Key here (explains table format and definitions)
Taxonomy | Taxonomy item | Relationship |
---|
ISO/IEC TR 24772:2013 |
Memory Leak [XYL] | Prior to 2018-01-12: CERT: Unspecified Relationship |
ISO/IEC TS 17961 |
Failing to close files or free dynamic memory when they are no longer needed [fileclose] | Prior to 2018-01-12: CERT: Unspecified Relationship | |
CWE 2.11 | CWE-401, Improper Release of Memory Before Removing Last Reference ("Memory Leak") | 2017-07-05: CERT: Exact |
CWE 2.11 | CWE-404 | 2017-07-06: CERT: Rule subset of CWE |
CWE 2.11 | CWE-459 | 2017-07-06: CERT: Rule subset of CWE |
CWE 2.11 | CWE-771 | 2017-07-06: CERT: Rule subset of CWE |
CWE 2.11 | CWE-772 | 2017-07-06: CERT: Rule subset of CWE |
CERT-CWE Mapping Notes
Key here for mapping notes
CWE-404/CWE-459/CWE-771/CWE-772 and FIO42-C/MEM31-C
Intersection( FIO42-C, MEM31-C) = Ø
CWE-404 = CWE-459 = CWE-771 = CWE-772
CWE-404 = Union( FIO42-C, MEM31-C list) where list =
- Failure to free resources besides files or memory chunks, such as mutexes)
Bibliography
[ISO/IEC 9899: |
2024] |
Subclause 7. |
24.3, "Memory Management Functions" |
...
...