开发者

strcpy() causes segmentation fault? [duplicate]

This question already has answers here: 开发者_高级运维 Closed 11 years ago.

Possible Duplicate:

Getting Segmentation Fault

Why does this code cause a segmentation fault?

char *text = "foo";
strcpy(text, "");

As far as I understand it, the first line allocates some memory (to hold the string "foo") and text points to that allocated memory. The second line copies an empty string into the location that text points to.

This code might not make a lot of sense, but why does it fail?


Whenever you have a string literal (in your case, "foo"), the program stores that value in a readonly section of memory.

strcpy wants to modify that value but it is readonly, hence the segmentation fault.

Also, text should be a const char*, not a char*.


Because a string literal (like "foo") is read-only.


Because the string literals are stored in the read only region of memory.

Thus attempting the modification of foo(using strcpy in this case) is an undefined behavior.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜