Why Segmentation fault in following code?

后端 未结 5 1227
忘了有多久
忘了有多久 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:34

    • When you do: char *s = "hello world"; then s is a pointer that points to a memory that is in the code part, so you can't change it.

    • When you do: char s[] = "Hello World"; then s is an array of chars that are on the stack, so you can change it.

    If you don't want the string to be changed during the program, it is better to do: char const *s = ....;. Then, when you try to change the string, your program will not crash with segmentation fault, it will arise a compiler error (which is much better).

提交回复
热议问题