Segmentation error while trying to change row

This code gives me a segmentation error at runtime.

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

Please tell me why?

+3
source share
4 answers

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.

+3
source

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];
+7
source

seg, "HELLO" - , , .

+7

This compiles to a string literal in a read-only section.

        .section        .rodata
.LC0:
        .string "HELLO"
+4
source

All Articles