()printf的执行与分割故障 [英] Execution of printf() and Segmentation Fault
本文介绍了()printf的执行与分割故障的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
#include<stdio.h>
int main()
{
char *name = "Vikram";
printf("%s",name);
name[1]='s';
printf("%s",name);
return 0;
}
有没有打印输出端子和刚刚获得分段错误。但是,当我在GDB运行它,我获得以下 -
There is no output printed on terminal and just get segmentation fault. But when I run it in GDB, I get following -
Program received signal SIGSEGV, Segmentation fault.
0x0000000000400525 in main () at seg2.c:7
7 name[1]='s';
(gdb)
这意味着程序接收七号线赛格故障(显然我不能常字符数组写)。那么,为什么行号的printf()6不执行?
This means program receive SEG fault on 7th line (obviously I can't write on constant char array) . Then why printf() of line number 6 is not executed ?
推荐答案
这是由于流标准输出
的缓冲。除非你做 fflush(标准输出)
或打印一个新行\\ n
输出可被缓冲。
This is due to stream buffering of stdout
. Unless you do fflush(stdout)
or you print a newline "\n"
the output is may be buffered.
在这种情况下,它被冲洗和打印缓冲器之前的段错误。
In this case, it's segfaulting before the buffer is flushed and printed.
您可以改为试试这个:
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)
这篇关于()printf的执行与分割故障的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文