As noted in undefined behavior 179 of Annex J of the C standard Standard [ISO/IEC 9899:2011], the behavior a program is undefined when
...
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; } |
Section 7.22.3 of the C standard Standard [ISO/IEC 9899:2011] states:
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.
and And Section 7.22.3.5 states:
If memory for the new object cannot be allocated, the old object is not deallocated and its value is unchanged.
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 common but nonconforming implementations that free the pointer, including the following:
- Glibc (GNU/Linux)
- AIX
- HP-UX
- Solaris
- OSF/1
...
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
| 484 S | Fully implemented. | |||||||
Fortify SCA | V. 5.0 | Double Free | |||||||
Splint |
| ||||||||
| RESOURCE_LEAK | Finds resource leaks from variables that go out of scope while owning a resource. | |||||||
| USE_AFTER_FREE | Can find the instances where a freed memory is freed again. Coverity Prevent cannot discover all violations of this rule, so further verification is necessary. | |||||||
Compass/ROSE | Can detect some violations of this rule. In particular, false positives may be raised if a variable is freed by a different function than the one that allocated it. Also, it is unable to warn on cases where a call to | ||||||||
| MLK |
...
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
CERT C Secure Coding Standard | MEM04-C. Do not perform zero-length allocations |
CERT C++ Secure Coding Standard |
...
...
...
...
TR 24772:2013 | Dangling Reference to Heap [XYK] Memory Leak [XYL] |
ISO/IEC TS 17961 (Draft) | Freeing memory multiple times [dblfree] |
...
...
...
Double free |
...
Bibliography
[ISO/IEC 9899:2011] | Section 7.22.3, "Memory Management Functions" |
[MIT 2005] | |
[OWASP |
...
Double Free] | "Double Free" |
[Viega 2005] | "Doubly |
...
Freeing Memory" | |
[VU#623332] |
...