linux-sysprog · intermediate · ~15 min

Read an integer environment variable with bounds

Parse-and-validate-then-use, with explicit range bounds.

Challenge

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. Returns -1 if getval is NULL or empty.
  2. Parses an integer from the entire string (no trailing garbage; optional leading -).
  3. Returns -1 if parsing fails or the result is outside [lo, hi].
  4. On success, stores the value in *out and returns 0.

Examples

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

Why this matters

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.

Input format

Value string + lo + hi + out pointer.

Output format

0 (success) or -1.

Constraints

Use strtol. Reject any trailing garbage.

Starter code

int env_int_in_range(const char *getval, int lo, int hi, int *out) { /* TODO */ return -1; }

Common mistakes

Using atoi — no error reporting. Forgetting to check *endptr == '\0'. Allowing whitespace, which is friendly but ambiguous.

Edge cases to handle

NULL; empty; negative numbers; leading + sign; overflow of long.

Complexity

O(strlen).

Background lessons

Up next

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