The result of calling
calloc() to allocate 0 bytes (
calloc(0,1)) is undefined. From a practical standpoint, allocating 0 bytes with
malloc() can lead to programming errors with critical security implications, such as buffer overflows. This occurs because the result of allocating 0 bytes with
malloc() may not considered an error, thus the pointer returned may not be
NULL. Instead, the pointer may reference a block of memory on the heap of size zero. If memory is fetched from, or stored in this a location serious error could occur.
Non-compliant Code Example 1
In this example, a dynamic array of integers is allocated to store
s elements. However, if
s is zero, the call to
malloc(s) will return a reference to a block of memory of size 0. When data is copied to this location, a heap-buffer overflow will occur.
Compliant Code Example 1
To assure that zero is never passed as a size argument to
malloc(), a check must be made on
s to assure it is not zero.
- Seacord 05 Chapter 4 Dynamic Memory Management