gpt4 book ai didi

c - 尝试打印 NULL 时的两种情况,一种有效,其他 SegFaults

转载 作者:太空狗 更新时间:2023-10-29 17:00:27 24 4
gpt4 key购买 nike

在以下内容中:

printf("Example%s\n",NULL);
printf("%s\n",NULL);

我得到的输出是:

Example(null)
Segmentation Fault

当我在 GDB 中尝试回溯时,它显示 printf() 已转换为 puts()。但我似乎无法理解为什么会这样。

顺便说一句,我找到了 this文章,但似乎仍然没有意义。

最佳答案

标准规定将 NULL 指针作为参数传递给带有 %s 说明符的 printf 是未定义的行为1(即任何事情都可能发生),因此这两种行为都是合法的。

在第一种情况下,标准库(特别是 printf 代码)通过打印 (null) 帮了您一个忙。

相反,在第二种情况下,优化器理解您的 printf 可以替换为 puts(效率更高)而不会对“可观察的行为”进行任何更改"的程序,所以它取代了它。但是,puts 并没有恰好包含 printfNULL 检查代码,因此您会遇到段错误。


  1. C99,§7.19.6.1,¶8:

    the argument shall be a pointer to the initial element of an array of character type.

    ¶9:

    If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.

    您属于最后一种情况,因为 NULL 不是“指向字符类型数组的初始元素的指针。

关于c - 尝试打印 NULL 时的两种情况,一种有效,其他 SegFaults,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10096502/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com