Versions Compared

Key

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

...

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.

This includes all three standard memory allocation functions: malloc(), calloc(), and realloc(). In cases where the memory allocation functions return a non-NULL null pointer, using this pointer results in undefined behavior. Typically these pointer refer 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.

...

The realloc() function for gcc 3.4.6 with libc 2.3.4 returns a non-NULL null pointer to a zero-sized object (the same as malloc(0)). However, the realloc() function for both Microsoft Visual Studio Version 7.1 and gcc version 4.1.0 return a NULL null pointer, resulting in a double free on the call to free() in this example.

...