Versions Compared

Key

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

When the requested size is zero is 0, the behavior of the memory allocation functions malloc(), calloc(), and realloc() is implementation-defined. Section 7.22.3 of the C standard Standard [ISO/IEC 9899:2011] states:

...

In addition, the amount of storage allocated by a successful call to the allocation function when 0 bytes was requested is unspecified. See unspecified behavior 41 in section J.1 of the standardC Standard.

In cases where the memory allocation functions return a non-null pointer, reading from or writing to the allocated memory area 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.

...

Compliant Solution

To ensure that zero 0 is never passed as a size argument to malloc(), size is checked to ensure to confirm it has a positive value.

Code Block
bgColor#ccccff
langc
size_t size;

/* initialize size, possibly by user-controlled input */

if (size == 0) {
  /* Handle error */
}
int *list = (int *)malloc(size);
if (list == NULL) {
  /* Handle allocation error */
}
/* Continue processing list */

...

The realloc() function deallocates the old object and returns a pointer to a new object of a specified size. If memory for the new object cannot be allocated, the realloc() function does not deallocate the old object, and its value is unchanged. If the realloc() function returns NULL, failing to free the original memory will result in a memory leak. As a result, the following idiom is often recommended for reallocating memory:

...

Risk Assessment

Allocating zero 0 bytes can lead to abnormal program termination.

...

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

Related Guidelines

...

ISO/IEC 9899:2011 Section 7.22.3, "Memory management functions"

...

...

Function call with incorrectly specified argument value

...

Bibliography Bibliography

[

...

ISO/IEC 9899:2011]Section 7.22.3, "Memory Management Functions"
[Seacord 2005a]Chapter 4, "Dynamic Memory Management"
[Vanegue 2010]"Automated Vulnerability Analysis of Zero-Sized Heap Allocations"

...