静态C字符串分配问题 [英] Static C string allocation question
问题描述
考虑以下code:
char* str = "Hello World";
memcpy(str, "Copy\0", 5);
在memcpy的过程中出现分段错误。但是,使用此code:
A segmentation fault occurs during the memcpy. However, using this code:
char str[12];
memcpy(str, "Hello World\0", 12);
memcpy(str, "Copy\0", 5);
该程序不会产生分段错误。
The program does not produce a segmentation fault.
问题是否从堆栈与数据部分的分配内存出现?
Does the problem arise from allocating the memory on the stack versus the data section?
推荐答案
当你使用一个字符串字面GCC的价值被放置在只读存储器,不能修改。试图修改它会导致不确定的行为。通常当你尝试这样做,你将获得在Linux分割故障。
When you use a string literal in gcc the value is placed in read-only memory and cannot be modified. Trying to modify it leads to undefined behaviour. Usually you will get a segmentation fault on Linux when you try to do this.
第二个例子的作品,因为你没有修改字符串,您正在修改存储在变量的副本是不是只读的。
The second example works because you aren't modifying the string literal, you are modifying a copy of it that is stored in variable that is not read-only.
这篇关于静态C字符串分配问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!