pointers-memory · intermediate · ~14 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.Drill: practice one contract before combining it with other skills.
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.
out points to a live writable int and is never NULL. Return 1 and store the sum when representable, else return 0 leaving *out unchanged. Do not perform signed overflow.
#include <limits.h>
int checked_add(int a, int b, int *out) {
/* TODO */
return 0;
}
Adding before checking, or modifying *out when reporting failure.
Positive overflow; negative underflow; exact INT_MIN/INT_MAX boundaries; zero; unchanged output after rejection.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.