-2
int main(void) {
char *temp = "ABCDE";
temp[2] = 'X';
printf("%s", temp);
return 0;
}

In gdb I could see that temp[2] = 'X' is causing the crash. But why? Could some answer please?

NeilB
  • 347
  • 2
  • 16
  • Because bad things happen when you attempt to modify a "*string-literal*" perhaps using a *character array*, `char temp[] = "ABCDE";` would be a better choice. – David C. Rankin Feb 20 '16 at 20:38

1 Answers1

4

String literals are non-modifiable. It may be stored in read-only section of the memory and any attempt to modify it will lead to undefined behavior.

If you want to modify it, declare temp as an array of chars

char temp[] = "ABCDE";
haccks
  • 104,019
  • 25
  • 176
  • 264