You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 30 Next »

The result of calling malloc(0) or calloc() - calloc(1,0), calloc(0,0), or calloc(0,1) - to allocate 0 bytes is implementation defined. 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 be 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 that location, a 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.

...
list = malloc(sizeof(int) * s);
if (list == NULL) {
  /* Handle Allocation Error */
}
/* Continue Processing list */
...

Compliant Code Example 1

To ensure that zero is never passed as a size argument to malloc(), a check must be made on s to ensure it is not zero.

...
if (s <= 0) {
  /* Handle Error */
}
list = malloc(sizeof(int) * s);
if (list == NULL) {
  /* Handle Allocation Error */
}
/* Continue Processing list */
...

Risk Assessment

Assuming that allocating zero bytes results in an error can lead to buffer overflows when zero bytes are allocated. Buffer overflows can be exploited by an attacker to run arbitrary code with the permissions of the vulnerable process.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

MEM36-C

3 (high)

2 (probable)

2 (medium)

P12

L1

References

  • No labels