linux-sysprog · intermediate · ~15 min
Parse-and-validate-then-use, with explicit range bounds.
Implement int env_int_in_range(const char *getval, int lo, int hi, int *out).
The first argument is the value string (so the test can pass NULL or arbitrary text). The function:
-1 if getval is NULL or empty.-).-1 if parsing fails or the result is outside [lo, hi].*out and returns 0.env_int_in_range("8080", 1, 65535, &out) -> 0, out == 8080
env_int_in_range("0", 1, 65535, &out) -> -1 // below lo
env_int_in_range("99999", 1, 65535, &out) -> -1 // above hi
env_int_in_range("8080x", 1, 65535, &out) -> -1 // trailing garbage
env_int_in_range(NULL, 1, 65535, &out) -> -1
env_int_in_range("", 1, 65535, &out) -> -1
Environment variables are attacker-influenceable in many deployment contexts (containers, init systems, CI). Treating them as untrusted input and validating both the format and the value range is one of the easiest hardening wins.
Value string + lo + hi + out pointer.
0 (success) or -1.
Use strtol. Reject any trailing garbage.
int env_int_in_range(const char *getval, int lo, int hi, int *out) { /* TODO */ return -1; }
Using atoi — no error reporting. Forgetting to check *endptr == '\0'. Allowing whitespace, which is friendly but ambiguous.
NULL; empty; negative numbers; leading + sign; overflow of long.
O(strlen).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.