
Integer values used as a size argument to malloc()
, calloc()
, or realloc()
can be manipulated by an attacker to cause a buffer overflow. Integer overflow or truncation can result in the allocation of an inadequately size buffer. The programmer must ensure that size arguments to memory allocation functions are valid and have not been corrupted as the result of an exceptional integer conditoin.
Non-compliant Code Example 1
In the following non-compliant code example, cBlocks
is multiplied by 16 and the result is stored in the unsigned long long int alloc
. The result of this multiplication can overflow because it is a 32 bit operation and the resulting value stored in alloc
is invalid.
void* AllocBlocks(size_t cBlocks) { if (cBlocks == 0) return NULL; unsigned long long alloc = cBlocks * 16; return (alloc < UINT_MAX) ? malloc(cBlocks * 16) : NULL; }
Compliant Solution 1
On architectures where {{unsigned long long int is guaranteed to have 2x the number of bits as size_tupcast the variable used in the multiplication to a 64-bit value. This ensures the multiplication operation is performed
void* AllocBlocks(size_t cBlocks) { if (cBlocks == 0) return NULL; unsigned long long alloc = (unsigned long long)cBlocks * 16; return (alloc < UINT_MAX) ? malloc(cBlocks * 16) : NULL; }
The assumption concerning the relationship of unsigned long long int and size_t must be document in the header for each file that depends upon this assumption for correct execution.
References
ISO/IEC 9899-199 Section 7.20.3 Memory Management Functions