basics · intermediate · ~30 min
Defensive parsing with sign + overflow handling.
Parse a string into an int, rejecting anything malformed — unlike atoi, which silently returns 0 on garbage.
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).
A NUL-terminated string s, and a pointer out where the parsed value is written on success.
Returns 0 on success with *out set to the integer; returns -1 on empty input, missing digits, trailing characters, or overflow.
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)
"" (empty) and "+" (sign with no digits) both return -1."-2147483648" (INT_MIN) is valid even though its magnitude exceeds INT_MAX.strtol/atoi — do the digit arithmetic yourself.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.
A NUL-terminated string s, and an int *out for the result.
0 on success (with *out set); -1 on any error.
No strtol/atoi; detect overflow before truncating. INT_MIN must parse.
int atoi_strict(const char *s, int *out) { /* TODO */ return -1; }
Allowing trailing garbage; accepting empty after the sign ("+" alone); doing the overflow check after the multiply (too late — already overflowed).
INT_MIN parsing: -2147483648 — must NOT overflow even though 2147483648 is > INT_MAX.
O(strlen).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.