I met some unexcepted result of strtol
in c
Here is the sample program.
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("%x\n", strtol("0xfffff70A", NULL, 0));
return 0;
}
and the output of this simple program is
0x7fffffff
rather than 0xfffff70A
.
And if I use strtoul
, the result is exactly 0xfffff70a
.
I am using a 32-bit machine, and I wonder what happens.
PS. I am using gcc 4.7.2
From 7.22.1.4 paragraph 8 (of the N1570 draft of the 2011 edition of the standard):
If the correct value is outside the range of representable values,
LONG_MIN
,LONG_MAX
,LLONG_MIN
,LLONG_MAX
,ULONG_MAX
, orULLONG_MAX
is returned (according to the return type and sign of the value, if any), and the value of the macroERANGE
is stored in errno.
Since the correct value of your input string is too large for the type, you get LONG_MAX
, and errno
is set to ERANGE
.
Whenever one of the strto(u)l(l)
functions returns one of the TYPE_MAX
or TYPE_MIN
values, you need to check errno
to find out whether it's a correct result, or your input was out-of-range.
You're running into overflow of the long
type, which is signed.
You probably should use:
print("%lx\n", strtoul("0xfffff70a", NULL, 0));
^
|
important!
instead, note the 'u' for "unsigned" (see manual page).
Also note that you can't print an unsigned long
with plain %x
, you need to qualify it as being bigger than int
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With