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.
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.
#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;
}overflowThe 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.