Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different results when using atoi() for C in Mac OS X and Ubuntu

Tags:

c

atoi

glibc

Here's the code which I ran on Mac OS X (10.8.1, 64-bit and 10.6.8, 32-bit) and Ubuntu (10.04, 32-bit):

printf("%d\n", atoi("2147483648"));
// returns -2147483648 in Mac OS X 10.8.1 and 10.6.8
// returns 2147483647 in Ubuntu

Here's what I found after some Googling: http://gynvael.coldwind.pl/?id=365

Is there any reason why the output varies on different systems?

like image 889
Alan Avatar asked Jan 16 '23 15:01

Alan


1 Answers

This is not surprising, because the behavior is not specified by the standard:

There is no standard specification on what happens when the converted value would be out of the range of representable values by an int.

The strtol function gives you more info in the return, as it sets errno to ERANGE when the value does not fit in a long int.

like image 146
Sergey Kalinichenko Avatar answered Jan 25 '23 23:01

Sergey Kalinichenko