Before the lifetime of the last pointer object that stores the return value of a call to a standard memory allocation function has ended, it must be matched by a call to a standard memory deallocation function 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 last pointer object (text_buffer
) referring to the object.
#include <stdlib.h> int f(void) { char *text_buffer = (char *)malloc(BUFSIZ); if (text_buffer == NULL) { return -1; } return 0; }
Compliant Solution
In this compliant solution, the pointer object that stores the return value from malloc()
is stored in a variable of static storage duration.
#include <stdlib.h> char *text_buffer; int f(void) { text_buffer = (char *)malloc(BUFSIZ); if (text_buffer == NULL) { return -1; } return 0; }
Risk Assessment
Freeing memory multiple times can result in an attacker executing arbitrary code with the permissions of the vulnerable process.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
MEM31-C | High | Probable | Medium | P12 | L1 |
Automated Detection
Tool | Version | Checker | Description |
---|---|---|---|
2017.07 | RESOURCE_LEAK | Finds resource leaks from variables that go out of scope while owning a resource | |
5.0 | Double Free | ||
2024.3 | MLK | ||
9.7.1 | 484 S | Fully implemented | |
3.1.1 |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
CERT C++ Secure Coding Standard | MEM31-CPP. Free dynamically allocated memory exactly once |
ISO/IEC TR 24772:2013 | Memory Leak [XYL] |
ISO/IEC TS 17961 | Failing to close files or free dynamic memory when they are no longer needed [fileclose] |
MITRE CWE | CWE-415, Double free |
Bibliography
[ISO/IEC 9899:2011] | Subclause 7.22.3, "Memory Management Functions" |