pointers-memory · intermediate · ~15 min
Detect undefined-behaviour overflow before it happens.
Add two ints safely by detecting signed overflow before it happens (since signed overflow is undefined behaviour in C, you must test for it rather than perform the add and inspect the result).
Implement int checked_add(int a, int b, int *out) that, when a + b fits in an int, stores the sum in *out and returns 1; on overflow it returns 0 and leaves *out unchanged. No main — the grader calls it.
a, b — the operands. out — where to store the sum on success.
Returns 1 with *out = a + b when the sum fits; returns 0 and leaves *out untouched on overflow/underflow.
checked_add(2, 3, &o) -> 1, o == 5
checked_add(INT_MAX, 1, &o) -> 0, o unchanged
checked_add(INT_MIN, -1, &o) -> 0, o unchanged
a + b > INT_MAX): return 0.a + b < INT_MIN): return 0.INT_MAX/INT_MIN; do not compute a + b and check afterwards.a, b — operands; out — destination for the sum on success.
1 with *out = a + b on success; 0 (out unchanged) on overflow.
Detect overflow before adding (signed overflow is UB); don't compute then check.
#include <limits.h>
int checked_add(int a, int b, int *out) {
/* TODO */
return 0;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.