Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does writing to a string literal in this C program segfault?

Tags:

c

#include<stdio.h>

void main()
{
    char *p="nyks";

    p[2]='n';

    printf("%s",p);
}

This crashes with a SEGMENTATION FAULT. Can someone explain why?

like image 716
Kraken Avatar asked Sep 03 '10 19:09

Kraken


2 Answers

It is undefined behavior to try to overwrite a string literal. C99 §6.4.5/6:

If the program attempts to modify such an array, the behavior is undefined.

This is restated in Appendix J.2 (undefined behavior).

If you instead do:

char p[] = "nyks";

you can allocate and initialize an automatic (stack) character array. In that case, it is perfectly fine to modify elements.

like image 191
Matthew Flaschen Avatar answered Oct 04 '22 03:10

Matthew Flaschen


The standard dictates that literal strings are defined const. You cannot change it.

The compiler places the literal in a readonly memory section. You can output the assembly and observe this. If you are using GCC it is done via the -s flag. It will place the string in a .rodata section.

like image 43
linuxuser27 Avatar answered Oct 04 '22 02:10

linuxuser27