Pointers and Strings causing segmentation fault [duplicate]

徘徊边缘 提交于 2019-12-13 05:58:19

问题


Possible Duplicate:
What is the difference between char a[] = “string”; and char *p = “string”;

char *str = "Hello";
printf("%c",++*str);

This gives segmentation fault on linux with gcc. The moment the first statement is changes to as

char str[10] = "Hello";

It works. What may be the reason?


回答1:


It is undefined behaviour to attempt to modify a string literal.

The compiler is free to place it in read-only memory (as it probably does in your case). Attempting to modify read-only memory is what's probably triggering the segfault.




回答2:


This statement char *str = "Hello"; stores the string "Hello" in RO-section and assigns the address of the area of RO-section(in which "Hello"is stored) to str. The data stored in RO-section cannot be modified thus you are getting a segfault.

char str[10] = "Hello";

is also wrong. You should instead write

char str[10];
strncpy(str,"Hello",sizeof(str));


来源:https://stackoverflow.com/questions/11098074/pointers-and-strings-causing-segmentation-fault

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!