Why is this an issue?
Using free(...)
or delete
releases the reservation on a memory location, making it immediately available for another
purpose. So releasing the same memory location twice can lead to corrupting the program’s memory.
A best practice to avoid this bug calls for setting just-freed pointers to NULL
, and always null-testing before a free
or
delete
.
Noncompliant code example
void doSomething(int size) {
char *cp = (char *) malloc(sizeof(char) * size);
// ...
if (condition) {
free(cp);
}
free(cp); // Noncompliant
}
Compliant solution
void doSomething(int size) {
char *cp = (char *) malloc(sizeof(char) * size);
// ...
if (condition) {
free(cp);
cp = NULL; // This will prewent freeing the same memory again
}
free(cp); // This is OK: if the memory was freed in the if-block above, free(NULL) is a no-op
cp = NULL; // This will prevent freeing the same memory again
}
Resources