简体   繁体   English

strtol未检测到整数溢出

[英]strtol not detecting integer overflow

I'm trying to convert a character array into an integer using strtol using the below code: 我正在尝试使用strtol使用以下代码将字符数组转换为整数:

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

Where temp = 4000000010 当温度= 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. 但是strtol不会检测到溢出,它不会将foo设置为LONG_MAX,并且errno不会从其初始值0更改。

Instead bob is changed to the overflowed value of -294967286. 取而代之的是将bob更改为-294967286的溢出值。

So I was wondering what am I missing here? 所以我想知道我在这里想念什么吗?

溢出可能发生在语句中的隐式longint转换中,而不是在strtol()内部。

If you know you will get large numbers, why not use strtoll instead? 如果您知道将获得大量数字,为什么不使用strtoll代替呢? Of course, like others remarked, then you definitively can't use an int to store the result. 当然,就像其他人提到的那样,那么您绝对不能使用int来存储结果。

  • You cannot store a variable of 4*10^9 in a 32-bit long. 您不能在32位长中存储4 * 10 ^ 9的变量。 long is signed by default. 默认情况下,long是签名的。
  • The maximum value of a long is (2^32 / 2)-1 = 2147483674, assuming long is 32 bit on your system. 假设long在系统上为32位,则long的最大值为(2 ^ 32/2)-1 = 2147483674。
  • Use strtoul () instead. 使用strtoul ()代替。
  • Change foo to unsigned long . 将foo更改为unsigned long

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM