与strcpy的分段错误() [英] Segmentation fault with strcpy()
问题描述
本作品:
int main()
{
char *t = "Hello";
t = "World";
printf("%s", t);
}
但是这给分段错误:
But this gives segmentation fault:
int main()
{
char *t = "Hello";
strcpy(t, "World"); // the only difference
printf("%s", t);
}
为什么?
推荐答案
这是你明确地定义字符串 - 例如你好
- 通常放置在只读存储器的一个区域。这些字符串不能被改变。
Strings that you define explicitly - e.g. "Hello"
- are typically placed in an area of read-only memory. These strings cannot be changed.
在第一个例子,你是不是改变了你好串入世界的字符串。您重新分配 T
,以便它的百分点的以世界,而不是你好。在你好字符串还在闲逛的,不变的,在只读存储器中。
In the first example, you are not changing the "Hello" string into the "World" string. You are re-assigning t
so that it points to "World" instead of "Hello". The "Hello" string is still hanging around, untouched, in read-only memory.
下面是初始状态:
t -> "Hello"
"World"
下面是第二个状态:
"Hello"
t -> "World"
在第二个例子中,你正在尝试覆盖你好字符串。这不能做。
In the second example, you are trying to overwrite the "Hello" string. This cannot be done.
您应该真正改变从的char * T
您声明为const char * T
。我认为,GCC可以配置为强制执行此。
You should really change your declaration from char *t
to const char *t
. I think GCC can be configured to enforce this.
这篇关于与strcpy的分段错误()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!