#include<stdio.h>
int main()
{
char *name = "Vikram";
printf("%s",name);
name[1]='s';
printf("%s",name);
return 0;
}
终端上没有打印输出,只是出现段错误。但是当我在 GDB 中运行它时,我得到了关注 -
Program received signal SIGSEGV, Segmentation fault.
0x0000000000400525 in main () at seg2.c:7
7 name[1]='s';
(gdb)
这意味着程序在第 7 行收到 SEG 错误(显然我不能在常量字符数组上写入)。那为什么第6行的printf()没有执行呢?
最佳答案
这是由于 stdout
的流缓冲。除非您执行 fflush(stdout)
或打印换行符 "\n"
,否则输出可能会被缓冲。
在这种情况下,它在缓冲区被刷新和打印之前发生了段错误。
你可以试试这个:
printf("%s",name);
fflush(stdout); // Flush the stream.
name[1]='s'; // Segfault here (undefined behavior)
或:
printf("%s\n",name); // Flush the stream with '\n'
name[1]='s'; // Segfault here (undefined behavior)
关于c - 执行 printf() 和 Segmentation Fault,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9469790/