Wiki Markup |
---|
The results of allocating zero bytes of memory using {{malloc()}}, {{calloc()}}, or {{realloc()}} are [implementation-defined|BB. Definitions#implementation-defined behavior]. According to C99 Section 7.20.3 \[[ISO/IEC 9899-:1999|AA. C References#ISO/IEC 9899-1999]\]: |
If the size of the space requested is zero, the behavior is implementation-defined: either a NULL 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.
In cases where the memory allocation functions return a non-NULL null pointer, using this pointer results in undefined behavior. Typically the pointer refers to a zero-length block of memory consisting entirely of control structures. Overwriting these control structures will damage the data structures used by the memory manager.
...
However, this commonly recommended idiom has problems with zero-length allocations. If the value of nsize
in this example is 0, the standard allows the option of either returning a NULL null pointer or returning a pointer to an invalid (e.g., zero-length) object. In cases where the realloc()
function frees the memory but returns a NULL null pointer, execution of the code in this example results in a double free.
...
If this non-compliant code is compiled with gcc 3.4.6 and linked with libc 2.3.4, invoking realloc(p, 0)
returns a non-NULL null pointer to a zero-sized object (the same as malloc(0)
). However, if the same code is compiled with either Microsoft Visual Studio Version 7.1 or gcc version 4.1.0 , realloc(p, 0)
returns a NULL null pointer, resulting in a double-free vulnerability.
...
Wiki Markup |
---|
\[[ISO/IEC 9899-:1999|AA. C References#ISO/IEC 9899-1999]\] Section 7.20.3, "Memory Management Functions" \[[Seacord 05|AA. C References#Seacord 05]\] Chapter 4, "Dynamic Memory Management" |
...