Site Tools


wiki:stdckdint.h

Table of Contents

stdckdint.h

Signed integer overflow in C is undefined behaviour. Unsigned overflow wraps silently. Both have caused real security bugs — length calculations that overflow and produce a smaller allocation than expected, counters that wrap around to zero. stdckdint.h (C23) gives you checked arithmetic macros that perform the operation and tell you whether it overflowed, without triggering UB.

#include <stdckdint.h>
 
int result;
if (ckd_add(&result, a, b)) {
    // overflow occurred; result is unspecified
    handle_overflow();
} else {
    // result holds a + b, no overflow
    use(result);
}

Three operations are provided: ckd_add, ckd_sub, ckd_mul. Each takes a pointer to the result and two operands. It returns true if the operation overflowed (for any combination of signed/unsigned types), false otherwise. The result type is inferred from the pointer.

unsigned int sum;
if (ckd_add(&sum, UINT_MAX, 1u))
    puts("overflow");   // printed: UINT_MAX + 1 overflows unsigned int
 
long product;
if (ckd_mul(&product, 1000000L, 1000000L))
    puts("overflow");   // on 32-bit long: overflows

Before C23, the overflow check for unsigned addition was if (a > UINT_MAX - b), and for signed required a careful pre-check or a compiler builtin like __builtin_add_overflow. The <stdckdint.h> macros are the portable, readable replacement — the logic reads like what it does rather than like a puzzle.

wiki/stdckdint.h.md · Last modified: by 127.0.0.1