Secure Coding in C · intermediate · ~10 min

Integer overflow

Avoid silent wraparound bugs.

Lesson

Signed integer overflow is undefined behaviour in C. Unsigned overflow wraps modulo 2^N. Either way, expressions like n * sizeof(T) can wrap silently and lead to small allocations and big writes (CWE-190).

Defences: check before multiplying (n > SIZE_MAX / sizeof(T)), use __builtin_mul_overflow (gcc/clang), or use checked-arithmetic wrappers.

Code examples

size_t n;  // user-controlled
if (n > SIZE_MAX / sizeof(T)) return -1;
T *a = malloc(n * sizeof(T));