cybersecurity · intermediate · ~20 min
Pre-check overflow in signed arithmetic to avoid UB.
Add two ints, detecting overflow before it happens. Signed overflow is undefined behaviour in C, so you cannot test a + b < a after the fact — the compiler may delete the check.
Implement int add_safe(int a, int b, int *out) that stores a + b in *out only when it fits in an int.
Do the check before adding, using:
INT_MAX: b > 0 && a > INT_MAX - bINT_MIN: b < 0 && a < INT_MIN - ba, b: the two ints to add.out: where the sum is written on success.Returns 0 on success (with *out = a + b), or -1 on overflow (leaving *out unchanged).
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
INT_MAX + 0 and INT_MIN + 0 succeed.INT_MAX + 1 overflows up; INT_MIN + -1 overflows down.__builtin_add_overflow) — do the math by hand.a + b before the check.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 a, b, and an output pointer out.
0 on success (with *out = a + b); -1 on overflow (with *out unchanged).
Check before adding; no __builtin_* overflow helpers.
#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.