...
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 allocation error */ } strcpy(str, argv[1]); } else { str = "usage: $>a.exe [string]"; printf("%s\n", str); } /* ... */ free(str); return 0; } |
Compliant Solution
This compliant solution eliminates the possibility of str
, referencing nondynamic non-dynamic memory when it is supplied 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 allocation error */ } strcpy(str, argv[1]); } else { printf("%s\n", "usage: $>a.exe [string]"); return -1; } /* ... */ free(str); return 0; } |
Noncompliant Code Example (realloc()
)
...
Code Block | ||||
---|---|---|---|---|
| ||||
#define#include <stdlib.h> enum { BUFSIZE = 256 }; void f(void) { char buf[BUFSIZE]; char *p; /* ... */ p = (char *)realloc(buf, 2 * BUFSIZE); /* violation */ /* ... */ } |
Compliant Solution(realloc()
)
...
Code Block | ||||
---|---|---|---|---|
| ||||
#define#include <stdlib.h> enum { BUFSIZE = 256 }; void f(void) { char *buf = (char *)malloc(BUFSIZE * sizeof(char)); char *p; /* ... */ p = (char *)realloc(buf, 2 * BUFSIZE); /* violation */ /* ... */ } |
Exceptions
MEM34-EX1: Some library implementations accept and ignore a deallocation of nonallocated memory (or, alternatively, cause a runtime-constraint violation). If all libraries used by a project have been validated as having this behavior, then this rule can be ignored.
...
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
CERT C Secure Coding Standard | MEM31-C. Free dynamically allocated memory exactly once |
CERT C++ Secure Coding Standard | MEM34-CPP. Only free memory allocated dynamically |
ISO/IEC TS 17961 (Draft) | Reallocating or freeing memory that was not dynamically allocatied [xfree] |
MITRE CWE | CWE-590, Free of invalid pointer not on the heap |
...
[Seacord 2013] | Chapter 4, "Dynamic Memory Management" |
[ISO/IEC 9899:2011] | Annex J, subclause J.2, "Undefined behavior" |
...