4

This code is giving me a segmentation fault at run time.

char *str = "HELLO";
str[0] = str[2];

Please can anyone tell me why?

Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272
  • Who is upvoting this ? Not a bad question but stackexchange will reach the point where it will detect this question and be able to point users at the c-faq. – cnicutar May 27 '11 at 08:11

4 Answers4

7

You cannot modify the contents of a string literal. Put it in a character array if you wish to be able to do so.

char str[] = "HELLO";
str[0] = str[2];
Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272
7

You're getting a seg-fault because the compiler has placed the string constant "HELLO" into read-only memory - and attempting to modify the string is thus failing.

Will A
  • 24,780
  • 5
  • 50
  • 61
4

This is compiled to a string literal in the read only section.

        .section        .rodata
.LC0:
        .string "HELLO"
Santhosh
  • 891
  • 3
  • 12
  • 31
3

Standard does not allow modifying a string literal. The string is stored in a readonly segment of the program, for example in linux, it is stored in the .rodata section of the executable which cannot be written.

phoxis
  • 60,131
  • 14
  • 81
  • 117