The result of calling malloc(0), or calling calloc()
to allocate 0 bytes (calloc(1,0)
, calloc(0,0)
, or calloc(0,1)
) is undefined. From a practical standpoint, allocating 0 bytes with calloc()
and malloc()
can lead to programming errors with critical security implications, such as buffer overflows. This occurs because the result of allocating 0 bytes with calloc()
and 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. Numerous, vulnerabilities may allow the allocation of 0 bytes with calloc and malloc, such as VU#179014, VU#226184, and VU#855118.
Non-compliant Code Example 1
...
Code Block |
---|
size_t str_size = calc_size(other_string); if (str_size > 0) { char *str_copy = malloc(str_size); if (str_copy == NULL) { /* handle error */ } strcpy(str_copy, other_string); } |
References
- Seacord 05 Chapter 4 Dynamic Memory Management