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

2019-02-06 23:56:23 +08:00
 ZoneN233

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 标准,(如果我没理解错) 应该是

2642 次点击
所在节点    程序员
4 条回复
geelaw
2019-02-07 00:16:06 +08:00
你对 endptr 的理解是错误的。它会得到被识别为第一个非数字的字符位置。

至于第一段代码,你没发现参数个数都是错误的吗?因为在 stdio 里这个函数没有声明,它的签名会默认为 int (...),所以你可以编译通过,链接的时候会默认链接到标准库,所以链接也能通过。我没查阅标准,不过可以想象这样是未定义行为或者未指定行为。
ZoneN233
2019-02-07 00:23:56 +08:00
@geelaw 原来如此,我是搞清楚没有函数声明的情况下是啥情况。thx
smdbh
2019-02-07 00:28:21 +08:00
man strtol
msg7086
2019-02-07 01:52:26 +08:00
# 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"));
~~~~~~ ^

不管是哪个编译器都警告你了。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/533252

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX