strcpy() 导致分段错误?
可能的重复:
获取分段错误
为什么此代码会导致分段错误?
char *text = "foo";
strcpy(text, "");
据我了解,第一行分配一些内存(用于保存字符串“foo”),并且 text
指向分配的内存。第二行将一个空字符串复制到 text
指向的位置。
这段代码可能没有多大意义,但为什么会失败呢?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
每当您有字符串文字(在您的例子中为“foo”)时,程序都会将该值存储在内存的只读部分中。
strcpy
想要修改该值,但它是只读的,因此出现分段错误。另外,
text
应该是const char*
,而不是char*
。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 aconst char*
, not achar*
.因为字符串文字(如
"foo"
)是只读。Because a string literal (like
"foo"
) is read-only.因为字符串文字存储在内存的只读区域中。
因此,尝试修改
foo
(在本例中使用strcpy
)是一种未定义行为。Because the string literals are stored in the read only region of memory.
Thus attempting the modification of
foo
(usingstrcpy
in this case) is an undefined behavior.