3

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
  • 121,762
  • 30
  • 236
  • 257
  • 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
  • 121,762
  • 30
  • 236
  • 257
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,392
  • 5
  • 48
  • 60
4

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

        .section        .rodata
.LC0:
        .string "HELLO"
Santhosh
  • 851
  • 3
  • 12
  • 30
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
  • 56,382
  • 14
  • 80
  • 112