【问题标题】:strtol not behaving as expected, cstrtol 未按预期运行,c
【发布时间】:2011-10-29 17:13:38
【问题描述】:
#include<limits.h>
#include<errno.h>

long output;

errno = 0;
output = strtol(input,NULL,10);
printf("long max = %ld\n",LONG_MAX);
printf("input = %s\n",input);
printf("output = %ld\n",output);
printf("direct call = %ld\n",strtol(input,NULL,10));
if(errno || output >= INT_MAX || output <= INT_MIN) {
    printf("Input was out of range of int, INT_MIN = %d, INT_MAX = %d\n",INT_MIN,INT_MAX);
    printf("Please input an integer within the allowed range:\n");
}

当上面的代码输入数组 {'1','2','3','4','5','6','7','8','9' ,'0','1'}

我得到一个输出:

long max = 9223372036854775807
input = 12345678901
output = -539222987
direct call = 3755744309

发生了什么... strtol 似乎正在遭受溢出但没有设置 errno

【问题讨论】:

    标签: c string int strtol


    【解决方案1】:

    您很可能没有包含必需的 &lt;stdio.h&gt; 和/或 &lt;stdlib.h&gt; 标头。

    包含这些代码后,您的代码可以正常工作(64 位模式下的 GCC):

    $ cat t.c
    #include<limits.h>
    #include<errno.h>
    #include<stdlib.h>
    #include<stdio.h>
    
    int main (void)
    {
        long output;
        char input[] = "12345678901";
        errno = 0;
        output = strtol(input,NULL,10);
        printf("long max = %ld\n",LONG_MAX);
        printf("input = %s\n",input);
        printf("output = %ld\n",output);
        printf("direct call = %ld\n",strtol(input,NULL,10));
        if(errno || output >= INT_MAX || output <= INT_MIN) {
            printf("Input was out of range of int, INT_MIN = %d, INT_MAX = %d\n",INT_MIN,INT_MAX);
            printf("Please input an integer within the allowed range:\n");
        }
        return 0;
    }
    
    $ gcc -Wall -Wextra -pedantic t.c
    $ ./a.out
    long max = 9223372036854775807
    input = 12345678901
    output = 12345678901
    direct call = 12345678901
    Input was out of range of int, INT_MIN = -2147483648, INT_MAX = 2147483647
    Please input an integer within the allowed range:
    

    顺便说一句,您应该在strtol 调用之后立即保存errno,您在strtol 和条件之间调用的库函数可能会改变它的值。

    【讨论】:

    • 谢谢,解决了!我有 stdio 但没有 stdlib,不知道这里需要它。感谢您指出 errno 问题。
    • @user1019856,你的编译器很可能会告诉你,如果你编译你的代码并打开所有警告,-Wall 左右。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-04
    • 1970-01-01
    • 1970-01-01
    • 2014-11-12
    • 1970-01-01
    • 2020-06-28
    相关资源
    最近更新 更多