Description
Using unchecked addition or multiplication results as allocation sizes can let unsigned arithmetic wrap and allocate less memory than required.
Potential impact
- Heap overflows, memory corruption, or denial of service may result.
Remediation
Check bounds before arithmetic. Before using division to check multiplication, ensure the divisor is not zero. Use checked arithmetic utilities where available.
Examples
Before
c
#include <stdlib.h>
void *allocate_array(size_t count, size_t size) {
return malloc(count * size);
}
After
c
#include <stdint.h>
#include <stdlib.h>
void *allocate_array(size_t count, size_t size) {
if (size == 0) { return NULL; }
if (count > SIZE_MAX / size) { return NULL; }
return malloc(count * size);
}
Explanation:
- Before: The multiplication result is used directly as the allocation size without checking for wrapping.
- After: The code first checks whether
sizeis zero to avoid division by zero, then allocates only when the multiplication does not exceedSIZE_MAX.