cybersecurity · intermediate · ~15 min
Pre-check overflow without performing the unsafe arithmetic.
Implement int sub_safe(int a, int b, int *out).
Return:
*out = a - b.int.Hint: a - b overflows above INT_MAX if b < 0 && a > INT_MAX + b. Below INT_MIN if b > 0 && a < INT_MIN + b.
Signed subtraction overflows in different cases than addition. Audit code rarely checks; the bug class is real in size calculations.
Two ints + output pointer.
0/-1 + (maybe) *out.
No GCC builtins; 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.