Why Segmentation fault in following code?

后端 未结 5 1294
忘了有多久
忘了有多久 2021-01-21 14:18

I read this on wikipedia

    int main(void)
 {

    char *s = \"hello world\";
    *s = \'H\';

 }

When the program containing this code is com

5条回答
  •  自闭症患者
    2021-01-21 14:35

    String literals are stored in read-only memory, that's just how it works. Your code uses a pointer initialized to point at the memory where a string literal is stored, and thus you can't validly modify that memory.

    To get a string in modifiable memory, do this:

    char s[] = "hello world";
    

    then you're fine, since now you're just using the constant string to initialize a non-constant array.

提交回复
热议问题