cybersecurity · intermediate · ~20 min
Pre-check overflow in signed arithmetic to avoid UB.
Implement int add_safe(int a, int b, int *out).
Return:
0 on success; *out holds a + b.-1 on overflow; *out is left unchanged.The check must be done before the addition, not after (a + b < a is undefined behaviour). Use the inequalities:
INT_MAX: b > 0 && a > INT_MAX - b.INT_MIN: b < 0 && a < INT_MIN - b.int out;
add_safe(1, 2, &out) -> 0, out == 3
add_safe(INT_MAX, 0, &out) -> 0, out == INT_MAX
add_safe(INT_MAX, 1, &out) -> -1, out unchanged
add_safe(INT_MIN, -1, &out) -> -1, out unchanged
add_safe(-5, 3, &out) -> 0, out == -2
Vulnerabilities like CVE-2002-0639 (OpenSSH challenge-response), Bash 'shellshock'-adjacent issues, and dozens of image-decoder CVEs (PNG / JPEG / GIF) all originate from missed integer-overflow checks before allocating or indexing.
Signed integer overflow is undefined behaviour in C — modern compilers will literally delete if (a + b < a) because they assume overflow can't happen. Real-world security bugs (image decoders, malloc-size calculations) come straight from this trap.
Two ints + output pointer.
0/-1 and (maybe) *out.
No GCC built-ins (__builtin_add_overflow) — do the math by hand.
#include <limits.h>
int add_safe(int a, int b, int *out) { /* TODO */ return -1; }
Adding first and then checking a + b < a — undefined behaviour. Mixing up the sign cases.
a == INT_MAX, b == 0 (success). INT_MAX + 1. INT_MIN + -1. -1 + 1.
O(1).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.