cybersecurity · intermediate · ~15 min · safe pentest lab
Prevent signed integer overflow and underflow vulnerabilities using pre-condition bounds checks.
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.
Implement:
int safe_int32_add(int32_t a, int32_t b, int32_t *result);
Add two signed 32-bit integers safely.
result == NULL, return -1.b > 0 and a > INT32_MAX - b, overflow would occur: return -1 without modifying *result.b < 0 and a < INT32_MIN - b, underflow would occur: return -1 without modifying *result.*result = a + b and return 0.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)
a, b: int32_t operands; result: pointer to int32_t output.
Returns 0 on success, -1 on overflow, underflow, or NULL pointer.
C11 freestanding. Never trigger signed integer overflow UB.
#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;
}
Performing a + b first and then checking (which is undefined behavior in C); forgetting underflow when b < 0.
Adding 0; INT32_MAX + 0; INT32_MIN + 0; INT32_MAX + (-1); NULL result pointer.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.