Khronos
Khronos

Reputation: 381

strtol not detecting integer overflow

I'm trying to convert a character array into an integer using strtol using the below code:

int foo = strtol(temp, (char **)NULL, 0);

Where temp = 4000000010

However strtol does not detect the overflow, it does not set foo to LONG_MAX and errno does not change from its inital value of 0.

Instead bob is changed to the overflowed value of -294967286.

So I was wondering what am I missing here?

Upvotes: 0

Views: 1272

Answers (3)

Lundin
Lundin

Reputation: 214265

  • You cannot store a variable of 4*10^9 in a 32-bit long. long is signed by default.
  • The maximum value of a long is (2^32 / 2)-1 = 2147483674, assuming long is 32 bit on your system.
  • Use strtoul() instead.
  • Change foo to unsigned long.

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409356

If you know you will get large numbers, why not use strtoll instead? Of course, like others remarked, then you definitively can't use an int to store the result.

Upvotes: 0

Pascal Cuoq
Pascal Cuoq

Reputation: 80325

The overflow probably occurs on the implicit long to int conversion in your statement, not inside strtol().

Upvotes: 3

Related Questions