Why shouldn't I use atoi()? [duplicate]

Someone told me that I shouldn't use atoi(), and that I should always use strtol() instead. What's wrong with atoi() that I shouldn't use it? Is strtol() really the right thing to use instead? (And what about the fact that strtol() returns a long, not an int like atoi() does?)


Solution 1:

from your own link:

The atoi() function is subsumed by strtol() but is retained because it is used extensively in existing code. If the number is not known to be in range, strtol() should be used because atoi() is not required to perform any error checking.

Or

atoi is obsolete

Solution 2:

With the atoi there is no way of finding out if the passed string really is a number, as there is no special error "return". It also only handles decimal values (base 10), so can't handle arbitrary bases like e.g. strtol. Also it can't handle values larger than signed integer (32 bits on most platforms).

Solution 3:

If string will be much large and can't be converted, it causes undefined behaviour as value of that string can be too large and that may not be in range. In such cases(where number is not known to be in range) strtol() should be used.