cybersecurity · intermediate · ~15 min · safe pentest lab

Signed 32-bit addition overflow guard

Prevent signed integer overflow and underflow vulnerabilities using pre-condition bounds checks.

Challenge

In C, signed integer overflow is Undefined Behavior. Compilers are permitted to optimize away naive post-facto checks like if (a + b < a). Overflow must be checked before the addition is performed.

Your Task

Implement:

int safe_int32_add(int32_t a, int32_t b, int32_t *result);

Add two signed 32-bit integers safely.

Rules

  1. If result == NULL, return -1.
  2. If b > 0 and a > INT32_MAX - b, overflow would occur: return -1 without modifying *result.
  3. If b < 0 and a < INT32_MIN - b, underflow would occur: return -1 without modifying *result.
  4. Otherwise, set *result = a + b and return 0.

Example

int32_t res = 0;
safe_int32_add(100, 200, &res); // returns 0, res = 300
safe_int32_add(INT32_MAX, 1, &res); // returns -1 (overflow)
safe_int32_add(INT32_MIN, -1, &res); // returns -1 (underflow)

Input format

a, b: int32_t operands; result: pointer to int32_t output.

Output format

Returns 0 on success, -1 on overflow, underflow, or NULL pointer.

Constraints

C11 freestanding. Never trigger signed integer overflow UB.

Starter code

#include <stdint.h>

/* Safely compute a + b for int32_t. Return 0 on success, or -1 on overflow/underflow
   or if result is NULL without modifying *result. */
int safe_int32_add(int32_t a, int32_t b, int32_t *result) {
    (void)a; (void)b; (void)result;
    return -1;
}

Common mistakes

Performing a + b first and then checking (which is undefined behavior in C); forgetting underflow when b < 0.

Edge cases to handle

Adding 0; INT32_MAX + 0; INT32_MIN + 0; INT32_MAX + (-1); NULL result pointer.

Background lessons

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.