V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
ZoneN233
V2EX  ›  程序员

用 stdio.h 调用 strtol() 与用 stdlib.h 调用,结果完全不一样,请问为什么啊

  •  
  •   ZoneN233 · 2019-02-06 23:56:23 +08:00 · 2606 次点击
    这是一个创建于 1898 天前的主题,其中的信息可能已经有所发展或是发生改变。

    stackoverflow

    #include "stdio.h"
    int main(void){
        printf("%ld\n", strtol("99999999999999999999999"));
        return 0;
    } # 0
    
    #include "stdio.h"
    //#include "stdlib.h"
    int main(void){
        char *end[500];
        printf("%ld\n", strtol("99999999999999999999999", end, 10));
        return 0;
    } # 9223372036854775807
    

    用 gcc 和 clang 结果一样。 按照 POSIX 标准,(如果我没理解错) 应该是

    • 将错误的字符串写入 endptr
    • 设置 ERANGE
    • 返回 LONG_MAX。
    4 条回复    2019-02-07 01:52:26 +08:00
    geelaw
        1
    geelaw  
       2019-02-07 00:16:06 +08:00 via iPhone   ❤️ 1
    你对 endptr 的理解是错误的。它会得到被识别为第一个非数字的字符位置。

    至于第一段代码,你没发现参数个数都是错误的吗?因为在 stdio 里这个函数没有声明,它的签名会默认为 int (...),所以你可以编译通过,链接的时候会默认链接到标准库,所以链接也能通过。我没查阅标准,不过可以想象这样是未定义行为或者未指定行为。
    ZoneN233
        2
    ZoneN233  
    OP
       2019-02-07 00:23:56 +08:00
    @geelaw 原来如此,我是搞清楚没有函数声明的情况下是啥情况。thx
    smdbh
        3
    smdbh  
       2019-02-07 00:28:21 +08:00
    man strtol
    msg7086
        4
    msg7086  
       2019-02-07 01:52:26 +08:00   ❤️ 1
    # gcc -o test test.c
    test.c: In function ‘ main ’:
    test.c:3:21: warning: implicit declaration of function ‘ strtol ’ [-Wimplicit-function-declaration]
    printf("%ld\n", strtol("99999999999999999999999"));
    ^~~~~~

    # clang -o test test.c
    test.c:3:21: warning: implicitly declaring library function 'strtol' with type 'long (const char *, char **, int)' [-Wimplicit-function-declaration]
    printf("%ld\n", strtol("99999999999999999999999"));
    ^
    test.c:3:21: note: include the header <stdlib.h> or explicitly provide a declaration for 'strtol'
    test.c:3:53: error: too few arguments to function call, expected 3, have 1
    printf("%ld\n", strtol("99999999999999999999999"));
    ~~~~~~ ^

    不管是哪个编译器都警告你了。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5191 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 08:06 · PVG 16:06 · LAX 01:06 · JFK 04:06
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.