...
| 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;
}
|
For example, if If size_t is represented as a 32-bit unsigned value and unsigned long long is represented as a 64-bit unsigned value, for example, the result of this multiplication can still overflow because the actual multiplication is a 32-bit operation. As a result, the value stored in alloc will always be less than UINT_MAX.
...
In this noncompliant code example, the string referenced by str and the string length represented by len originate from untrusted sources. The length is used to perform a memcpy() into the fixed-size static array buf. The len variable is guaranteed to be less than BUFF_SIZE. However, because len is declared as an int, it can have a negative value that would bypass the check. The memcpy() function implicitly converts len to an unsigned size_t type, and the resulting operation results in a buffer overflow.
...
| Code Block | ||
|---|---|---|
| ||
void function(size_t len) {
long *p;
if (len == 0 || len > SIZE_MAX / sizeof(long)) {
/* handleHandle overflow */
}
p = (long *)malloc(len * sizeof(int));
if (p == NULL) {
/* handleHandle error */
}
/* ... */
free(p);
}
|
...
| Code Block | ||
|---|---|---|
| ||
void function(size_t len) {
long *p;
if (len == 0 || len > SIZE_MAX / sizeof(long)) {
/* handleHandle overflow */
}
p = (long *)malloc(len * sizeof(long));
if (p == NULL) {
/* handleHandle error */
}
/* ... */
free(p);
}
|
...