basics · intermediate · ~30 min
Defensive parsing with sign + overflow handling.
Implement int atoi_strict(const char *s, int *out). Rules:
+ or - sign.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.
Null-terminated string.
0 on success (with *out set); -1 on any error.
No strtol. Implement the arithmetic yourself.
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.