...
In this noncompliant code example, an array of long is allocated and assigned to p. This example also checks for unsigned integer overflow in compliance with INT32-C. Ensure that operations on signed integers do not result in overflow. The code also ensures that len is not equal to zero. (See MEM04-C. Do not perform zero-length allocations.) However, sizeof(int) is used to size the allocated memory. If sizeof(long) is larger than sizeof(int), then an insufficient amount of memory is allocated.
| Code Block | ||||
|---|---|---|---|---|
| ||||
#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);
}
|
...
Compliant Solution (Size Calculation)
Alternatively,
sizeof(*p) can be used to properly size the allocation:| Code Block | ||||
|---|---|---|---|---|
| ||||
#include <stdlib.h>
void function(size_t len) {
long *p;
if (len == 0 || len > SIZE_MAX / sizeof(*p)) {
/* Handle overflow */
}
p = (long *)malloc(len * sizeof(*p));
if (p == NULL) {
/* Handle error */
}
free(p);
}
|
...