Description
Subtracting a header larger than the total length makes an unsigned result wrap to a large value. Converting a negative result to size_t can also produce a large allocation request.
Potential impact
The allocation can exhaust memory or fail, interrupting service.
Remediation
Check that the header fits within the total before subtracting. Also enforce the application’s allocation limit on the remaining length.
Examples
Before
c
#include <stdlib.h>
void *allocate(size_t total, size_t header) {
return malloc(total - header);
}
After
c
#include <stdlib.h>
void *allocate(size_t total, size_t header) {
if (total >= header) {
return malloc(total - header);
}
return NULL;
}
The example calls malloc only when total >= header. A larger header makes the function return NULL.