strtoll在溢出时未将errno设置为ERANGE

时间:2020-08-22 14:40:34

标签: c gcc linux-mint errno strtol

我正在像使用fgetsstrtoll一样解析long long值,但是当溢出时,strtoll并未将errno设置为ERANGE像预期的那样发生。

From the man page

strtol()函数将返回转换结果,除非该值下溢或上溢。如果发生下溢,则strtol()返回LONG_MIN如果发生溢出,strtol()返回LONG_MAX。在这两种情况下,errno都设置为ERANGE。完全相同strtoll()(用LLONG_MIN和LLONG_MAX代替LONG_MIN和LONG_MAX)

出于MRE目的,不带fgets的示例代码:

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <errno.h>

int main(){

    long long number; //max value 9223372036854775807   
    char input[] = "12345678976543245678976543";
    char *end;

    number = strtoll(input, &end, 10);

    printf("%d %d <%s> %lld %lld\n", errno, ERANGE, input, (long long)number, LLONG_MAX);
    //prints 0 for errno and 34 for ERANGE regardless of overflow
    //eerno should be set to ERANGE so it should be 34

    int e = errno; //further testing, assigning errno
    printf("%d", e);// again prints 0 should be 34
}

输出为:

0 34 <12345678976543245678976543> 9223372036854775807 9223372036854775807
0

应该是:

34 34 <12345678976543245678976543> 9223372036854775807 9223372036854775807
34

这让我感到非常困惑,尤其是因为in an online compiler似乎可以正常工作。

我正在最近更新的Linux Mint 20中使用gcc版本9.3.0(Ubuntu 9.3.0-10ubuntu2),ldd(Ubuntu GLIBC 2.31-0ubuntu9)2.31。

1 个答案:

答案 0 :(得分:1)

我重新安装了整个系统,现在问题消失了,我可能应该报告它,我比社区更多地考虑我的问题。

导致这些问题的可能情况是,我对升级系统的一些建议步骤视而不见。

间接证据:

  • 还有其他问题,例如 wifi 错误、GRUB 和时区问题,它们在新安装后也消失了。

  • 我也升级了我的桌面,只是想看看是否可以重现同样的问题,但这次仔细遵循所有步骤,一切正常。

所以对于升级 UNIX 系统的任何人,注意升级说明。并有备份,在这种情况下它救了我的命。

相关问题