If an integer expression is compared to, or assigned to, a larger integer size, then that integer expression should be evaluated in that larger size by explicitly casting one of the operands.
Non-Compliant
...
Code Example
This code example is non-compliant on systems where size_t is an unsigned 32-bit value and long long is a 64-bit value. In this example, the programmer tests for integer overflow by assigning the value UINT_MAX to max and testing if length + BLOCK_HEADER_SIZE > max. Because length is declared as size_t, however, the addition is performed as a 32-bit operation and can result in an integer overflow. The comparison with max in this example will always test false. If an overflow occurs, malloc() will allocate insufficient space for mBlock which could lead to a subsequent buffer overflow.
...
| Code Block | ||
|---|---|---|
| ||
void *AllocateBlock(size_t length) {
struct memBlock *mBlock;
if ((unsigned long long)length + BLOCK_HEADER_SIZE > max) return NULL;
mBlock = malloc(length + BLOCK_HEADER_SIZE);
if (!mBlock) return NULL;
/* fill in block header and return data portion */
return mBlock;
}
|
Non-Compliant
...
Code Example
In this non-compliant code example, the programmer attempts to prevent against integer overflow by allocating an unsigned long long integer called alloc and assigning it the result from cBlocks * 16.
...