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.
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; } |
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; } |
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 |
Tool | Version | Checker | Description |
---|---|---|---|
RESOURCE_LEAK | Finds resource leaks from variables that go out of scope while owning a resource | ||
5.0 | Double Free | ||
MLK | |||
484 S | Fully implemented | ||
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
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 |
[ISO/IEC 9899:2011] | Subclause 7.22.3, "Memory Management Functions" |