basics · intermediate · ~30 min

Strict atoi: parse an int with full error reporting

Defensive parsing with sign + overflow handling.

Challenge

Parse a string into an int, rejecting anything malformed — unlike atoi, which silently returns 0 on garbage.

Task

Implement int atoi_strict(const char *s, int *out) that parses s as a signed decimal integer. The accepted format is: optional leading spaces, an optional + or - sign, then one or more digits, and nothing else afterward. On success, write the value to *out and return 0. On any error, return -1 (and leave *out unchanged).

Input

A NUL-terminated string s, and a pointer out where the parsed value is written on success.

Output

Returns 0 on success with *out set to the integer; returns -1 on empty input, missing digits, trailing characters, or overflow.

Example

atoi_strict("42", &v)            ->   0,  v == 42
atoi_strict("  -7", &v)          ->   0,  v == -7
atoi_strict("12a", &v)           ->   -1  (trailing 'a')
atoi_strict("+", &v)             ->   -1  (no digits)
atoi_strict("9999999999", &v)    ->   -1  (overflow)

Edge cases

  • "" (empty) and "+" (sign with no digits) both return -1.
  • Trailing non-digit characters return -1.
  • "-2147483648" (INT_MIN) is valid even though its magnitude exceeds INT_MAX.

Rules

  • Do not call strtol/atoi — do the digit arithmetic yourself.

Why this matters

atoi(3) silently returns 0 on garbage — that's a notorious source of bugs. Building a strict parser teaches careful error handling and overflow guards.

Input format

A NUL-terminated string s, and an int *out for the result.

Output format

0 on success (with *out set); -1 on any error.

Constraints

No strtol/atoi; detect overflow before truncating. INT_MIN must parse.

Starter code

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

Common mistakes

Allowing trailing garbage; accepting empty after the sign ("+" alone); doing the overflow check after the multiply (too late — already overflowed).

Edge cases to handle

INT_MIN parsing: -2147483648 — must NOT overflow even though 2147483648 is > INT_MAX.

Complexity

O(strlen).

Up next

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