Why is this an issue?
Memory allocated dynamically with calloc(...)
, malloc(...)
, realloc(...)
or new
should be
released when it’s not needed anymore. Failure to do so will result in a memory leak that could bring the box to its knees.
This rule raises an issue when memory is allocated and not freed in the same function. Allocated memory is ignored if a pointer to it is
return
ed to the caller or stored in a structure that’s external to the function.
Noncompliant code example
int fun() {
char* name = (char *) malloc (size);
if (!name) {
return 1;
}
// ...
return 0; // Noncompliant, memory pointed by "name" has not been released
}
Compliant solution
int fun() {
char* name = (char *) malloc (size);
if (!name) {
return 1;
}
// ...
free(name);
return 0;
}
Resources
- MITRE, CWE-401 - Improper Release of Memory Before Removing Last Reference ('Memory
Leak')
- MEM00-C. - Allocate and free memory in the same module, at the same level of
abstraction
- CERT, MEM31-C. - Free dynamically allocated memory when no longer needed