As noted under undefined Undefined behavior 179, states that the behavior of a program is undefined when
...
Freeing memory that is not allocated dynamically can lead to result in heap corruption and other serious errors similar to those discussed in MEM31-C. Free dynamically allocated memory when no longer needed. The consequences of this error depend on the implementation, but they range from nothing to abnormal program termination. Regardless of the implementation, do . Do not call free()
on anything other than a pointer returned by a dynamic memory allocation function, such as malloc()
, calloc()
, realloc()
, or aligned_alloc()
.
...
This rule does not apply to null pointers. The standard officially declares that when given C Standard guarantees that if free()
is passed a null pointer, free()
does nothingno action occurs.
Noncompliant Code Example
...
This compliant solution eliminates the possibility of str
, referencing nondynamic memory when it is supplied referencing memory that is not allocated dynamically when passed to free()
:
Code Block | ||||
---|---|---|---|---|
| ||||
#include <stdlib.h> #include <string.h> enum { MAX_ALLOCATION = 1000 }; int main(int argc, const char *argv[]) { char *str = NULL; size_t len; if (argc == 2) { len = strlen(argv[1]) + 1; if (len > MAX_ALLOCATION) { /* Handle error */ } str = (char *)malloc(len); if (str == NULL) { /* Handle error */ } strcpy(str, argv[1]); } else { printf("%s\n", "usage: $>a.exe [string]"); return -1; } free(str); return 0; } |
...
Note that realloc()
will behave properly even if malloc()
failed, because when given a null pointer, realloc()
behaves like a call to malloc()
.
Risk Assessment
Freeing or reallocating memory that was not dynamically allocated can lead The consequences of this error depend on the implementation, but they range from nothing to arbitrary code execution if that memory is reused by malloc()
.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
MEM34-C | High | Likely | Medium | P18 | L1 |
...
CERT C Secure Coding Standard | MEM31-C. Free dynamically allocated memory when no longer needed |
CERT C++ Secure Coding Standard | MEM34-CPP. Only free memory allocated dynamically |
ISO/IEC TS 17961 | Reallocating or freeing memory that was not dynamically allocatied allocated [xfree] |
MITRE CWE | CWE-590, Free of invalid pointer not on the heap |
...