Versions Compared

Key

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

...

In this noncompliant code example, an array of long is allocated and assigned to pThe code attempts to check for unsigned integer overflow in compliance with INT30-C. Ensure that unsigned integer operations do not wrap and also ensures that len is not equal to zero. (See MEM04-C. Beware of zero-length allocations.) However, because sizeof(int) is used to compute the size, and not sizeof(long), an insufficient amount of memory can be allocated on implementations where sizeof(long) is larger than sizeof(int) , and filling the array can cause a heap buffer overflow.

Despite the overflow check, the multiplication in the call to malloc() still violates INT30-C.

Code Block
bgColor#FFcccc
langc
#include <stdint.h>
#include <stdlib.h>
 
void function(size_t len) {
  long *p;
  if (len == 0 || len > SIZE_MAX / sizeof(long)) {
    /* Handle overflow */
  }
  p = (long *)malloc(len * sizeof(int));
  if (p == NULL) {
    /* Handle error */
  }
  free(p);
}

...