...
In this noncompliant code example, an array of long is allocated and assigned to p. The 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 | ||||
|---|---|---|---|---|
| ||||
#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);
}
|
...