printf() 的执行和分段错误 [英] Execution of printf() and Segmentation Fault

查看:15
本文介绍了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) 

这意味着程序在第 7 行收到 SEG 错误(显然我不能在常量 char 数组上写入).那为什么不执行第 6 行的 printf() 呢?

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 ?

推荐答案

这是由于 stdout 的流缓冲造成的.除非您执行 fflush(stdout) 或打印换行符 " " 输出可能会被缓冲.

This is due to stream buffering of stdout. Unless you do fflush(stdout) or you print a newline " " 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
",name);   //  Flush the stream with '
'
name[1]='s';           //  Segfault here (undefined behavior)

这篇关于printf() 的执行和分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆