cybersecurity · intermediate · ~15 min

Parse a bounded unsigned int

Parse defensively with a value ceiling.

Challenge

Parse a non-negative decimal integer defensively, rejecting junk and capping the value so it can never overflow downstream.

Task

Implement int parse_uint_max(const char *s, int max, int *out) that parses s as a non-negative base-10 integer. Return 1 and write the value to *out if s is non-empty, all digits, and the value is <= max; otherwise return 0.

Input

  • s: a NUL-terminated candidate number the grader provides.
  • max: the inclusive upper bound.
  • out: where the parsed value is written on success.

Output

Returns 1 on success (with *out set), 0 on any failure.

Example

parse_uint_max("42", 100, &out)    ->   1, out = 42
parse_uint_max("200", 100, &out)   ->   0   (exceeds max)
parse_uint_max("4a", 100, &out)    ->   0   (non-digit)
parse_uint_max("", 100, &out)      ->   0   (empty)

Edge cases

  • Empty string: return 0.
  • Any non-digit character: return 0.
  • Value exceeding max: return 0 (check during accumulation to avoid overflow).

Input format

A NUL-terminated candidate s, an inclusive ceiling max, and an out pointer.

Output format

1 with *out set if s is all digits and <= max; otherwise 0.

Constraints

Require at least one digit, all digits; cap the value at max during parsing.

Starter code

int parse_uint_max(const char *s, int max, int *out) {
    /* TODO */
    return 0;
}

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