When the requested size is 0, the behavior of the memory allocation functions malloc()
, calloc()
, and realloc()
is implementation-defined. Section Subclause 7.22.3 of the C 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 subclause J.1 of the C 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 damages the data structures used by the memory manager.
...
The result of calling malloc(0)
to allocate 0 bytes is implementation-defined. In this example, a dynamic array of integers is allocated to store size
elements. However, if size
is 0, the call to malloc(size)
may return a reference to a block of memory of size 0 instead of a null pointer. When (nonempty) data is copied to this location, a heap-buffer overflow occurs.
...
Code Block | ||||
---|---|---|---|---|
| ||||
size_t nsize = /* someSome value, possibly user supplied */; char *p2; char *p = (char *)malloc(100); if (p == NULL) { /* Handle error */ } /* ... */ if ((p2 = (char *)realloc(p, nsize)) == NULL) { free(p); p = NULL; return NULL; } p = p2; |
...
Allocating 0 bytes can lead to abnormal program termination.
Recommendation | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
MEM04-C | lowLow | likelyLikely | mediumMedium | P6 | L2 |
Automated Detection
Tool | Version | Checker | Description |
---|---|---|---|
|
| Can detect some violations of this rule. In particular, it warns when the argument to |
...
CERT C++ Secure Coding Standard | MEM04-CPP. Do not perform zero-length allocations |
MITRE CWE | CWE-687, Function call with incorrectly specified argument value |
Bibliography
[ISO/IEC 9899:2011] | Section 7.22.3, "Memory Management Functions" |
[Seacord 2013] | Chapter 4, "Dynamic Memory Management" |
[Vanegue 2010] | "Automated Vulnerability Analysis of Zero-Sized Heap Allocations" |
...