开发者

Segmentation fault when trying to modify a string [duplicate]

开发者 https://www.devze.com 2023-03-08 22:17 出处:网络
This questio开发者_Go百科n already has answers here: Why do I get a segmentation fault when writing to a "char *s" initialized with a string literal, but not "char s[]"?
This questio开发者_Go百科n already has answers here: Why do I get a segmentation fault when writing to a "char *s" initialized with a string literal, but not "char s[]"? (19 answers) Closed 5 years ago.

This code is giving me a segmentation fault at run time.

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

Please can anyone tell me why?


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


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.


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

        .section        .rodata
.LC0:
        .string "HELLO"


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号