Versions Compared

Key

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

...

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.)

The C99 standard says (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.

and (7.20.3.4):

If memory for the new object cannot be allocated, the old object is not deallocated and its value is unchanged.

Some nonconforming implementations disagree with the standard when calling If realloc() is called with size equal to 0. These implementations , then if a NULL pointer is returned, the old value should be unchanged. However, there are some implementations that free the pointer that was passed as an argument and return a NULL pointer, so calling free() , which means that calling free on the original pointer may be is indeterminate.

Noncompliant Code Example

...