This code gives me a segmentation error at runtime.
char *str = "HELLO"; str[0] = str[2];
Please tell me why?
The standard does not allow changing a string literal. The string is stored in the readonly segment of the program, for example, on Linux, it is stored in the .rodataexecutable file section , which cannot be written.
.rodata
You cannot change the contents of a string literal. Put it in an array of characters if you want to do this.
char str[] = "HELLO"; str[0] = str[2];
seg, "HELLO" - , , .
This compiles to a string literal in a read-only section.
.section .rodata .LC0: .string "HELLO"