Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between strtol and strtoul?

Tags:

c

std

strtol

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

like image 775
user1668903 Avatar asked May 23 '13 10:05

user1668903


2 Answers

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.

like image 68
Daniel Fischer Avatar answered Nov 14 '22 23:11

Daniel Fischer


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.

like image 29
unwind Avatar answered Nov 15 '22 00:11

unwind