Integer underflow in allocation sizes

Integer underflow in allocation sizes

Description

Using an unchecked subtraction result as an allocation size can request much more memory than intended when unsigned arithmetic wraps or a negative result is converted to a large unsigned value.

Potential impact

  • Excessively large allocation requests, allocation failure, or denial of service may result.

Remediation

Before subtracting, check that the first operand is at least as large as the value being subtracted, and limit the result to an acceptable range.

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;
}

Explanation:

  • Before: When total is smaller than header, the wrapped result becomes the allocation size.
  • After: Both operands use the allocation-size type size_t. Subtraction and allocation occur only when total >= header.

References