cybersecurity · intermediate · ~20 min

Add two ints with overflow detection

Pre-check overflow in signed arithmetic to avoid UB.

Challenge

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.

Task

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:

  • overflow above INT_MAX: b > 0 && a > INT_MAX - b
  • overflow below INT_MIN: b < 0 && a < INT_MIN - b

Input

  • a, b: the two ints to add.
  • out: where the sum is written on success.

Output

Returns 0 on success (with *out = a + b), or -1 on overflow (leaving *out unchanged).

Example

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

Edge cases

  • INT_MAX + 0 and INT_MIN + 0 succeed.
  • INT_MAX + 1 overflows up; INT_MIN + -1 overflows down.

Rules

  • No GCC/Clang built-ins (__builtin_add_overflow) — do the math by hand.
  • Never compute a + b before the check.

Why this matters

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.

Input format

Two ints a, b, and an output pointer out.

Output format

0 on success (with *out = a + b); -1 on overflow (with *out unchanged).

Constraints

Check before adding; no __builtin_* overflow helpers.

Starter code

#include <limits.h>
int add_safe(int a, int b, int *out) { /* TODO */ return -1; }

Common mistakes

Adding first and then checking a + b < a — undefined behaviour. Mixing up the sign cases.

Edge cases to handle

a == INT_MAX, b == 0 (success). INT_MAX + 1. INT_MIN + -1. -1 + 1.

Complexity

O(1).

Background lessons

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.