سؤال

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, or ULLONG_MAX is returned (according to the return type and sign of the value, if any), and the value of the macro ERANGE 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.

Your architecture has a 32-bit long type. 0xfffff70A is not representable as a signed 32-bit long. errno should have been set to ERANGE.

In 2's complement, representable values for 32-bit signed integers range from -0x80000000 to 0x7fffffff.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top