...
In this noncompliant code example, num_blocks is multiplied by 16 and the result is stored in the alloc.:
| Code Block | ||||
|---|---|---|---|---|
| ||||
enum { BLOCKSIZE = 16 };
/* ... */
void *alloc_blocks(size_t num_blocks) {
if (num_blocks == 0) {
return NULL;
}
unsigned long long alloc = num_blocks * BLOCKSIZE ;
return (alloc < UINT_MAX)
? malloc(num_blocks * BLOCKSIZE )
: NULL;
}
|
...
In this compliant solution, len is declared as a size_t so there is no possibility of this variable having a negative value and bypassing the range check.:
| Code Block | ||||
|---|---|---|---|---|
| ||||
size_t len;
char *str;
char buf[BUFF_SIZE];
/* ... */
if (len < BUFF_SIZE){
memcpy(buf, str, len);
}
/* ... */
|
...
To correct the noncompliant code example, sizeof(long) is used to size the memory allocation.:
| Code Block | ||||
|---|---|---|---|---|
| ||||
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);
}
|
Alternatively, sizeof(*p) can be used to properly size the allocation.:
| Code Block | ||||
|---|---|---|---|---|
| ||||
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);
}
|
...
Tool | Version | Checker | Description | ||||||
|---|---|---|---|---|---|---|---|---|---|
Compass/ROSE |
|
| 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. | |||||||
Fortify SCA | 5.0 |
| Can detect violations of this rule with CERT C Rule Pack, except those involving the | ||||||
| 487 S | Fully implemented. |
Related Vulnerabilities
CVE-2009-0587 results from a violation of this rule. Before version 2.24.5, Evolution Data Server performed unchecked arithmetic operations on the length of a user-input string and used the value to allocate space for a new buffer. An attacker could thereby execute arbitrary code by inputting a long string, resulting in incorrect allocation and buffer overflow [xorl 2009].
...