Integer overflow in allocation sizes

Integer overflow in allocation sizes

Description

When adding or multiplying byte counts, an unsigned result that exceeds SIZE_MAX can wrap to a smaller size.

Potential impact

Writing the intended amount of data to that smaller buffer can corrupt heap memory or interrupt service.

Remediation

Before adding or multiplying, check that the result will fit in size_t. Use checked arithmetic when 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);
}

The function rejects a zero size before dividing. It multiplies only when count <= SIZE_MAX / size.

References