Execution of printf() and Segmentation Fault

Vikram picture Vikram · Feb 27, 2012 · Viewed 53k times · Source
#include<stdio.h>

int main()
{
    char *name = "Vikram";
    printf("%s",name);
    name[1]='s';
    printf("%s",name);
    return 0;
}

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) 

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 ?

Answer

Mysticial picture Mysticial · Feb 27, 2012

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.

You can try this instead:

printf("%s",name);
fflush(stdout);        //  Flush the stream.
name[1]='s';           //  Segfault here (undefined behavior)

or:

printf("%s\n",name);   //  Flush the stream with '\n'
name[1]='s';           //  Segfault here (undefined behavior)