Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

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 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 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 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 pointer--, resulting in a double-free vulnerability.

Compliant Code Example

...