Integer values used as a size argument to malloc(), calloc(), realloc(), or aligned_alloc() must be valid and large enough of sufficient size to contain the objects to be stored. If size arguments are incorrect or can be manipulated by an attacker, then a buffer overflow may occur. Incorrect size arguments, inadequate range checking, integer overflow, or truncation can result in the allocation of an inadequately sized buffer.
Typically the amount of memory to allocate will be the size of the type of object to allocate. When allocating space for an array, the size of the object will be multiplied by the bounds of the array. Use the correct type of the object when computing the size of chunk to allocate.
STR31-C. Guarantee that storage for strings has sufficient space for character data and the null terminator is a specific instance of this rule.
Noncompliant Code Example (Integer)
In this noncompliant code example, an array of long is allocated and assigned to p. This example also The code checks for unsigned integer overflow in compliance with INT32-C. Ensure that operations on signed integers do not result in overflow. The code and also ensures that len is not equal to zero . (See see MEM04-C. Beware of zero-length allocations.) HoweverUnfortunately, because sizeof(int) is used to size the allocated memory. If memory an insufficient amount of memory can be allocated on implementations where 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);
}
|
...
In this noncompliant code example, too little inadequate 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.
...
Tool | Version | Checker | Description | ||||||
|---|---|---|---|---|---|---|---|---|---|
|
| could check violations of this rule by examining the size expression to
| |||||||
| BAD_ALLOC_STRLEN
| Can find instances where string length is miscalculated (length calculated may be one less than intended) for memory allocation purposes. Coverity Prevent cannot discover all violations of this rule, so further verification is necessary Finds memory allocations that are assigned to a pointer that reference objects larger than the allocated block | |||||||
5.0 |
| Can detect violations of this rule with CERT C Rule Pack, except those involving the | |||||||
| 9.1 | INCORRECT.ALLOC_SIZE | ||||||||
| 487 S | Fully implemented | |||||||
| 3.1.1 |
Related Vulnerabilities
...
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
...