Search code examples
cstrtolc-standard-library

What is the difference between strtol and strtoul?


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


Solution

  • 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.