Wiki Markup |
---|
As noted in [undefined behavior 169|CC. Undefined Behavior#ub_169] of Annex J of \[[ISO/IEC 9899-1999|AA. Bibliography#ISO/IEC 9899-1999]\], the behavior a program is [undefined |BB. Definitions#undefined behavior] when |
...
To eliminate double-free vulnerabilities, it is necessary to guarantee that dynamic memory is freed exactly one time. Programmers should be wary when freeing memory in a loop or conditional statement; if coded incorrectly, these constructs can lead to double-free vulnerabilities. It is also a common error to misuse the realloc()
function in a manner that results in double-free vulnerabilities. (See recommendation MEM04-C. Do not perform zero length allocations.)
Wiki Markup |
---|
According to the C99 standard \[[ISO/IEC 9899-1999|AA. Bibliography#ISO/IEC 9899-1999]\] |
(7.20.3): |
If the size of the space requested is zero, the behavior is implementation defined: either a null pointer is returned, or the behavior is as if the size were some nonzero value, except that the returned pointer shall not be used to access an object.
...
If realloc()
is called with size
equal to 0, then if a NULL pointer is returned, the old value should be unchanged. However, there are some implementations that free the pointer, which means that calling free
on the original pointer might result in a double-free vulnerablility, however, not calling free
on the original pointer might result in a memory leak.
See Implementation-Specific 7.35 Performing zero length allocations (MEM04-C) for more information.
Noncompliant Code Example
In this example, p
may be freed twice.
Code Block | ||
---|---|---|
| ||
/* p is a pointer to dynamically allocated memory */ p2 = realloc(p, size); if(p2 == NULL) { free(p); /* p may be indeterminate when (size == 0) */ return; } |
Compliant Code Example
In this example, p
is freed exactly once.
Code Block | ||
---|---|---|
| ||
/* p is a pointer to dynamically allocated memory */
if(size) {
p2 = realloc(p, size);
if(p2 == NULL) {
free(p);
return;
}
}
else {
free(p);
return;
}
|
Noncompliant Code Example
In this noncompliant code example, the memory referred to by x
may be freed twice: once if error_condition
is true and again at the end of the code.
...
CERT C++ Secure Coding Standard: MEM31-CPP. Free dynamically allocated memory exactly once
CERT C Secure Coding Standard: MEM04-C. Do not perform zero length allocations
ISO/IEC TR 24772 "XYK Dangling Reference to Heap" and "XYL Memory Leak"
...