C strtol Validation: Why atoi("abc") Returns 0 and How to Fix It

In C, atoi("0") returns 0—and atoi("abc") also returns 0. There is no error flag, no exception, and no way to tell whether the user typed a valid zero or complete garbage.

1. The Counterexample

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    printf("atoi(\"0\")   = %d\n", atoi("0"));
    printf("atoi(\"abc\") = %d\n", atoi("abc"));
    printf("atoi(\"12x\") = %d\n", atoi("12x"));
    return 0;
}

Output:

atoi("0")   = 0
atoi("abc") = 0
atoi("12x") = 12

2. Why atoi() Is Unsafe

  • Returns 0 on non-numeric input, indistinguishable from real "0".
  • Silently accepts trailing garbage like "12x" as 12.
  • Triggers undefined behavior on integer overflow.

3. The Right Fix: Use strtol() with endptr and errno

#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>

int parse_int(const char *s, int *out) {
    char *end = NULL;
    errno = 0;
    long val = strtol(s, &end, 10);

    if (end == s || *end != '\0') return 0;
    if (errno == ERANGE || val < INT_MIN || val > INT_MAX) return 0;

    *out = (int)val;
    return 1;
}

int main(void) {
    const char *tests[] = {"0", "abc", "12x", "42"};
    for (int i = 0; i < 4; i++) {
        int value = 0;
        if (parse_int(tests[i], &value)) {
            printf("%-5s -> valid: %d\n", tests[i], value);
        } else {
            printf("%-5s -> Invalid integer\n", tests[i]);
        }
    }
    return 0;
}

Output:

0     -> valid: 0
abc   -> Invalid integer
12x   -> Invalid integer
42    -> valid: 42

Comments

Popular posts from this blog

Java Integer Overflow: Why Adding Positive Numbers Gives a Negative Sum

Why Excel Breaks Your Python CSV (1-Word UTF-8 BOM Fix)