...
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)
To correct the noncompliant code example, This compliant solution uses sizeof(long) is used to to correctly size the memory allocation:
| 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(long));
if (p == NULL) {
/* Handle error */
}
free(p);
}
|
Compliant Solution (Size Calculation)
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);
}
|
...
Noncompliant Code Example
In this noncompliant code example, too little space is allocated for a struct tm object because the size of the pointer is being used to determine the size of the pointed-to object. This is a demonstration of EXP01-C. Do not take the size of a pointer to determine the size of the pointed-to type.
...
In this compliant solution, the correct amount of memory is allocated for the struct tm object. When allocating space for a single object, passing the (dereferenced) pointer type to the sizeof operator is a simple way to allocate sufficient memory.
| Code Block | ||||
|---|---|---|---|---|
| ||||
#include <time.h>
struct tm *make_tm(int year, int mon, int day, int hour,
int min, int sec) {
struct tm *tmb;
tmb = (struct tm *)malloc(sizeof(*tmb));
if (tmb == NULL) {
return NULL;
}
tmb->tm_sec = sec;
tmb->tm_min = min;
tmb->tm_hour = hour;
tmb->tm_mday = day;
tmb->tm_mon = mon;
tmb->tm_year = year;
return tmb;
} |
...