Secure Coding in C · intermediate · ~10 min
Avoid silent wraparound bugs.
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.
size_t n; // user-controlled
if (n > SIZE_MAX / sizeof(T)) return -1;
T *a = malloc(n * sizeof(T));