c - 执行 printf() 和 Segmentation Fault

标签 c segmentation-fault printf

#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/

相关文章:

C 段错误 - 哪里/什么?

c - 将 LAPACKE_zgetrs 与 LAPACK_ROW_MAJOR 一起使用会导致非法内存访问

c++ - 在 D 中使用 C++ 类

c - 打印一个结构成员,该成员是指向另一个结构的指针?

c++ - sprintf 引起的 exc_bad_access

c - 从 C 文件中读取 64 位十六进制值

c - Malloc 语句给出段错误 11

c - 动态分配数组的未定义行为(段错误)

c - 在动态分配的数组中使用 sprintf 时出现段错误

C : File redirection is not working