cybersecurity · intermediate · ~15 min
Detect size_t addition wrap-around.
Add two size_t values, detecting the silent wrap-around that unsigned overflow causes.
Implement int safe_add_size(size_t a, size_t b, size_t *out) that stores a + b in *out and returns 0, or returns -1 if the addition would wrap past SIZE_MAX.
Check before adding: the sum wraps iff a > SIZE_MAX - b.
a, b: the two sizes to add.out: where the sum is written on success.Returns int: 0 on success (with *out = a + b), or -1 if it would wrap.
size_t o;
safe_add_size(10, 20, &o) -> 0, o == 30
safe_add_size(SIZE_MAX, 1, &o) -> -1 (wraps)
SIZE_MAX wraps for any positive b.a > SIZE_MAX - b before adding; never let the unsigned sum wrap.Two size_t values a, b, and an output pointer out.
An int: 0 on success (with *out = a+b), or -1 on wrap-around.
Check a > SIZE_MAX - b before adding.
#include <stdint.h>
#include <stddef.h>
int safe_add_size(size_t a, size_t b, size_t *out) {
/* TODO */
return -1;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.