As noted in undefined behavior 169179 of Annex J of [ISO/IEC 9899-1999:2011], the behavior a of a program is undefined when
the pointer argument to the
free
orrealloc
function does not match a pointer earlier returned bycalloc
,malloc
, orrealloc
, or the space has been deallocated by a call tofree
orrealloc
.
Freeing memory that is not allocated dynamically can lead to serious errors similar to those discussed in rule MEM31-C. Free dynamically allocated memory exactly once. The specific consequences of this error depend on the implementation, but they range from nothing to abnormal program termination. Regardless of the implementation, avoid calling free()
on anything other than a pointer returned by a dynamic-memory allocation function, such as malloc()
, calloc()
, or realloc()
.
...
Code Block | ||||
---|---|---|---|---|
| ||||
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;
}
|
...
Code Block | ||||
---|---|---|---|---|
| ||||
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;
}
|
...
Tool | Version | Checker | Description | section|||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| section483 S | sectionFully | Implemented sectionimplemented. | |||||||||||
| sectionBAD_FREE | |||||||||||||
Section | Identifies calls to | section. | ||||||||||||
| sectionFNH.MIGHT | |||||||||||||
Section | Compass/ROSE | |||||||||||||
Section | Can detect some violations of this rule. |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
...
CERT C++ Secure Coding Standard: MEM34-CPP. Only free memory allocated dynamically
ISO/IEC 9899:19992011 Section 7.2022.3, "Memory management functions"
ISO/IEC TR 17961 (Draft) Reallocating or freeing memory that was not dynamically allocatied [xfree]
MITRE CWE: CWE-590, "Free of Invalid Pointer Not on the Heap"
...