segmentation fault (core dumped) when changing str

2020-04-23 04:43发布

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

char *str = "string";
str[0] = 'S'; //segmentation fault(core dumped) 

标签: c
2条回答
叼着烟拽天下
2楼-- · 2020-04-23 05:18

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?

查看更多
家丑人穷心不美
3楼-- · 2020-04-23 05:21

char *str = "string"; points to a read-only part of memory and because of that the string can't be changed.

You need to declare an array instead of a pointer which points to an array if you want to change the array like this

char str[] = "string";
查看更多
登录 后发表回答