basics · intermediate · ~30 min

Strict atoi: parse an int with full error reporting

Defensive parsing with sign + overflow handling.

Challenge

Implement int atoi_strict(const char *s, int *out). Rules:

  • Skip leading spaces.
  • Optional + or - sign.
  • At least one digit must follow.
  • No trailing characters (after the digits).
  • Overflow → return -1.
  • Empty / garbage input → return -1.
  • Success → write the integer to *out, return 0.

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

Null-terminated string.

Output format

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

Constraints

No strtol. Implement the arithmetic yourself.

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.