cybersecurity · intermediate · ~15 min

Overflow-checked size addition

Detect size_t addition wrap-around.

Challenge

Add two size_t values, detecting the silent wrap-around that unsigned overflow causes.

Task

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.

Input

  • a, b: the two sizes to add.
  • out: where the sum is written on success.

Output

Returns int: 0 on success (with *out = a + b), or -1 if it would wrap.

Example

size_t o;
safe_add_size(10, 20, &o)        ->   0, o == 30
safe_add_size(SIZE_MAX, 1, &o)   ->   -1   (wraps)

Edge cases

  • Adding to SIZE_MAX wraps for any positive b.

Rules

  • Check a > SIZE_MAX - b before adding; never let the unsigned sum wrap.

Input format

Two size_t values a, b, and an output pointer out.

Output format

An int: 0 on success (with *out = a+b), or -1 on wrap-around.

Constraints

Check a > SIZE_MAX - b before adding.

Starter code

#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.