gpt4 book ai didi

c - 为什么这个 C 程序不会导致字母数字值的段错误?

转载 作者:行者123 更新时间:2023-11-30 19:57:43 25 4
gpt4 key购买 nike

该程序最简单的形式是

int main(){
int x;
scanf("%d",x);
}

当我们给这个程序提供任何数值作为输入时,它会失败并产生一个段错误信号,这正是我们所期望的。

但是如果我们给它任何字母数字值,它不会失败。

产生此行为的 scanf 中发生了什么?

这是使用数值运行 gdb 时的回溯:

(gdb) bt

#0 0x00000034e7456ed0 in _IO_vfscanf_internal () from /lib64/libc.so.6

#1 0x00000034e74646cd in __isoc99_scanf () from /lib64/libc.so.6

#2 0x0000000000400553 in main ()

那么为什么它对于任何字母数字值(如“a”或“dfgb”)都不会失败?

最佳答案

标准第 7.21.6.2/10 节说:

If the input item is not a matching sequence, the execution of the directive fails: this condition is a matching failure.

和 7.21.6.2/4:

The fscanf function executes each directive of the format in turn. When all directives have been executed, or if a directive fails (as detailed below), the function returns. Failures are described as input failures (due to the occurrence of an encoding error or the unavailability of input characters), or matching failures (due to inappropriate input).

由于您的输入没有提供良好的可解析整数,因此 scanf 仅返回 0 以表示未对输入进行任何转换,并且不要尝试取消引用您传递的参数。

这个答案经过编辑以引用有关这一点的标准,感谢@Zwol

关于c - 为什么这个 C 程序不会导致字母数字值的段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38528466/

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