I wish to take an integer as a command line argument, but if the user passes a non-integer string, this will cause a stack overflow. What is the standard way to ensure atoi() will be successful?
相关问题
- Multiple sockets for clients to connect to
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
- Index of single bit in long integer (in C) [duplic
- Equivalent of std::pair in C
I don't think a standard atoi will stackoverflow, but there's no way to tell if you don't have an integer with it. Use
strtol
instead -- it's possible to deal with non-integers.http://en.wikipedia.org/wiki/Strtol
Cause a stack overflow? Well I suppose that's one possible result of the undefined behavior if the value in the string overflows the range of
int
. In practice though it usually just wraps or returns a bogus result.If you want better error checking, use
strtol
instead ofatoi
. It has well-defined behavior on overflow (it setserrno
, which you need to clear to 0 before callingstrtol
so you can distinguish between error returns and legitimate values being returned) and you can examine the point in the string at which it stopped conversion to see if the full string was an integer or whether there's additional content past the end.You can use:
long int strtol(const char *nptr, char **endptr, int base);
Then check if
*endptr != nptr
. This means that the string at least begins with the integer. You can also check that *endptr points to terminating zero, which means that the whole string was successfully parsed.atoi()
will (should) not cause a stack overflow if the string contains characters other than digits. It will simply convert to anint
any digit it finds from the beginning of the string until there is no more.You may check that there is no integer overflow (number outside the range of [-2^31, 2^31-1] on a modern (current) PC architecture).
edit (comments)
While the C standards warns about an undefined behavior if the value cannot be represented, the most common C recent compilers (gcc, MS...) do not crash if the value is not acceptable (unless the
char *
pointer is null or wrong of course).Anyway, you can implement your own
atoi()
easily (with the same limitations as in my answer)This might help you. Check strtol available in stdlib.h
This does not cause stack overflow.
atoi
returns0
if it can't find a number at the start of the string. Your (non-)handling of the0
is what causes the stack overflow.