1

Why changing string characters causes segmentation fault(core dumped):

char *str = "string";
str[0] = 'S'; //segmentation fault(core dumped) 
Tom
  • 385
  • 3
  • 7
  • 17
  • 1
    Please use search first http://stackoverflow.com/questions/1704407/what-is-the-difference-between-char-s-and-char-s-in-c – Abhi Sep 11 '14 at 18:09

2 Answers2

3

The solution is simple, declare your string in the following way instead

  char str[] = "string";

The reason why you should do this is because of the Undefined behavior. Creating a string with pointers will make your string locate at the read only memory part, so you cannot modify it, whereas another way will also make a copy of your string on the stack. Also check What is the difference between char s[] and char *s in C?

Community
  • 1
  • 1
betteroutthanin
  • 7,148
  • 8
  • 29
  • 48
  • 1
    You cannot say both "undefined behavior" and "**will make**" (a definitive statement). The point of "undefined behavior" is that anything can happen, and nothing is required to happen. It is *likely* that your string will be located in read-only memory, but not required. – abelenky Sep 11 '14 at 18:15
  • @abelenky Thanks for pointing out, I'm not a native english speaker, and the undefined behavior says that the one like the question is one of the undefined behavior. – betteroutthanin Sep 11 '14 at 18:18
2

char *str = "string"; points to a read-only part of memory and because of that the string can't be changed.

You need to declare an array instead of a pointer which points to an array if you want to change the array like this

char str[] = "string";
Igor Pejic
  • 3,658
  • 1
  • 14
  • 32