Versions Compared

Key

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

...

the pointer argument to the free or realloc function does not match a pointer earlier returned by calloc, malloc, or realloc, or a memory management function, or the space has been deallocated by a call to free or realloc.

...

Code Block
bgColor#FFCCCC
langc
/* 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;
}

According to the Section 7.22.3 of the C standard [ISO/IEC 9899:2011] (7.22.3)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 (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 non-conforming nonconforming implementations that free the pointer including:

...

In this compliant solution, allocations of zero - bytes are prevented, ensuring that p is freed exactly once.

...

ISO/IEC TR 24772 "XYK Dangling Reference reference to Heapheap" and "XYL Memory Leakleak"

MITRE CWE: CWE-415, "Double Freefree"

Bibliography

[MIT 2005]
[OWASP, Double Free]
[Viega 2005] "Doubly Freeing Memoryfreeing memory"
[VU#623332]

...