Skip to content
systemcoding.dev
Security

Detect multiplication overflow with __builtin_mul_overflow

Use __builtin_mul_overflow in GCC 14 or Clang to multiply two sizes and learn whether the product wrapped, before it reaches malloc.

1 min read
Summarize in AI

The classic allocation bug is malloc(count * size) where the product wraps past SIZE_MAX and the buffer comes back far too small. Checking afterwards is too late, and checking before with a division is easy to get wrong. GCC and Clang provide __builtin_mul_overflow(a, b, &result), which stores the wrapped product and returns true if the real one did not fit.

mul.cc
#include <stddef.h>
#include <stdio.h>

int main(void)
{
    size_t count = (size_t)1 << 62;
    size_t size = 8;
    size_t total;

    if (__builtin_mul_overflow(count, size, &total))
        puts("overflow");
    else
        printf("%zu\n", total);
    return 0;
}
Text
overflow

The result type is taken from the pointer, so the check is done in that type and mixed signedness is handled correctly, which a hand-written test often gets wrong. There are matching add and sub forms. C23 standardises the idea as ckd_mul in <stdckdint.h>, which GCC 14 ships, but the builtin works on older compilers too. For arrays specifically, reallocarray does the same check inside libc. The builtins are documented under Integer Overflow Builtins.

Taggedcgcc
Share

More snippets

Systems Programming

Get the page size with sysconf(_SC_PAGESIZE)

Read the memory page size at run time with sysconf(_SC_PAGESIZE) instead of hard-coding 4096, which is wrong on arm64 kernels built with 16K or 64K pages.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.