为什么这个 C 程序不会导致字母数字值的分段错误?
Why is this C program NOT causing a segmentation fault with alphanumeric values?
程序的最简单形式是
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
只需 returns 0 表示没有从输入进行转换,并且不要尝试取消引用您传递的参数。
编辑此答案以引用有关该点的标准,感谢@Zwol。
程序的最简单形式是
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
只需 returns 0 表示没有从输入进行转换,并且不要尝试取消引用您传递的参数。
编辑此答案以引用有关该点的标准,感谢@Zwol。