atoi — how to identify the difference between zero and error?

That’s one of the reasons atoi is sometimes considered unsafe. Use strtol / strtoul instead. And if you have it use strtonum.

The function atoi is more dangerous than you might think. The POSIX standard says:

If the value cannot be represented, the behavior is undefined.

The C99 standard says this also:

7.20.1

The functions atof, atoi, atol, and atoll need not affect the value of
the integer expression errno on an error. If the value of the result
cannot be represented, the behavior is undefined.

Leave a Comment