cybersecurity · intermediate · ~15 min

Strict integer parsing

Distinguish "permissive" parsing from strict input validation — a foundational security mindset.

Challenge

Parse an integer strictly: accept only a clean signed-decimal string and reject everything else.

Task

Implement int parse_safe_int(const char *s, int *out) that accepts a string made up only of an optional leading - followed by one or more decimal digits, stores the value in *out, and returns 0. Anything else returns -1. No main — the grader calls it.

Input

  • s: the candidate string (NUL-terminated).
  • out: pointer that receives the parsed value on success.

Output

Returns 0 and sets *out for a valid string; returns -1 for an invalid one.

Example

parse_safe_int("42", &v)    ->   0, v = 42
parse_safe_int("-7", &v)    ->   0, v = -7
parse_safe_int(" 5", &v)    ->   -1   (leading space)
parse_safe_int("+5", &v)    ->   -1   (plus sign)
parse_safe_int("5abc", &v)  ->   -1   (trailing junk)
parse_safe_int("", &v)      ->   -1

Edge cases

  • Empty string, a lone -, leading/trailing whitespace, a + sign, or any trailing non-digit all fail.

Rules

  • Reject; do not silently accept partial input. Require at least one digit and end-of-string after the digits.

Input format

A candidate string s and an out pointer for the result.

Output format

0 with *out set for a clean signed-decimal string; -1 otherwise.

Constraints

Allow only optional leading - and digits; reject spaces, +, and trailing junk.

Starter code

int parse_safe_int(const char *s, int *out) {
    /* TODO */
    return -1;
}

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