cybersecurity · intermediate · ~15 min
Pre-check overflow without performing the unsafe arithmetic.
Subtract two ints, detecting overflow before it happens. Signed subtraction overflows in different cases than addition, and audit code rarely checks it.
Implement int sub_safe(int a, int b, int *out) that stores a - b in *out only when it fits in an int.
Check before subtracting, using:
INT_MAX: b < 0 && a > INT_MAX + bINT_MIN: b > 0 && a < INT_MIN + ba, b: the minuend and subtrahend.out: where the difference is written on success.Returns 0 on success (with *out = a - b), or -1 if the subtraction would overflow int.
int out;
sub_safe(5, 3, &out) -> 0, out == 2
sub_safe(INT_MAX, -1, &out) -> -1 (overflows up)
sub_safe(INT_MIN, 1, &out) -> -1 (overflows down)
sub_safe(0, 0, &out) -> 0, out == 0
sub_safe(-5, -3, &out) -> 0, out == -2
INT_MAX - (-1) overflows up; INT_MIN - 1 overflows down.0 - 0 succeeds.Signed subtraction overflows in different cases than addition. Audit code rarely checks; the bug class is real in size calculations.
Two ints a, b, and an output pointer out.
0 on success (with *out = a - b); -1 on overflow (with *out unchanged).
Check before subtracting; no __builtin_* helpers; portable C.
#include <limits.h>
int sub_safe(int a, int b, int *out) { /* TODO */ return -1; }
Doing a - b first and then comparing — undefined.
INT_MIN - 1; INT_MAX - (-1); 0 - 0; INT_MIN - INT_MIN.
O(1).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.