C

Lesson 08

Integer overflow before allocation

Check multiplication before allocating arrays so a wrapped byte count does not create a too-small buffer.

Good Code

src/review_scores.c
#include <stdint.h>
#include <stdlib.h>

int allocate_scores(size_t count, int **out)
{
    // Check multiplication before asking malloc for bytes.
    if (out == NULL || count > SIZE_MAX / sizeof **out) {
        return -1;
    }

    *out = malloc(count * sizeof **out);
    return *out == NULL ? -1 : 0;
}

Bad Code

review_scores.c
#include <stdlib.h>

int *allocate_scores(size_t count)
{
    // Overflow can make malloc reserve fewer bytes than requested.
    return malloc(count * sizeof(int));
}

Review Notes

What to review

Good Code

The good version checks that count * sizeof **out fits in size_t before allocating. The output pointer is written only after the size is proven.

Bad Code

The bad version multiplies directly inside malloc. If the multiplication wraps, the loop that fills the array can write past the smaller allocation.

Takeaways

  • Allocation math must be checked before malloc, because overflow can turn a large request into a small allocation.