segmentation fault (core dumped) when changing string characters

前端 未结 2 486
予麋鹿
予麋鹿 2021-01-24 13:24

Why changing string characters causes segmentation fault(core dumped):

char *str = \"string\";
str[0] = \'S\'; //segmentation fault(core dumped) 
2条回答
  •  醉话见心
    2021-01-24 14:14

    The solution is simple, declare your string in the following way instead

      char str[] = "string";
    

    The reason why you should do this is because of the Undefined behavior. Creating a string with pointers will make your string locate at the read only memory part, so you cannot modify it, whereas another way will also make a copy of your string on the stack. Also check What is the difference between char s[] and char *s in C?

提交回复
热议问题