C 堆栈分配
Possible Duplicate:
Why does this Seg Fault?
Is the stack allocation is read only:
char* arr="abc";
arr[0]='c';
Can you change the string that is allocated on the stack??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
字符串
"abc"
不在堆栈中。指向它的指针 (arr
) 是。修改字符串文字是未定义的行为。您可以在 GCC 在 x86 上生成的 asm 中清楚地看到这一点:
The string
"abc"
isn't on the stack. A pointer to it (arr
) is. Modifying the string literal is undefined behaviour.You can see this quite clearly in the asm GCC generates on x86:
您的代码不会在堆栈上分配字符串。它在堆栈上分配一个
char*
,即一个指针,并使该指针指向字符串文字。尝试修改字符串文字是未定义的行为。要在堆栈上分配字符串,请执行以下操作:
现在,您已在堆栈分配的数组
arr
中获取了字符串文字的副本,并且您可以修改该副本。对于完整的迂腐:我所描述的“堆栈分配”的所有内容在技术上都是“自动变量”。 C 本身并不关心它们被分配在哪里,但我可以很有信心地猜测您的实现实际上确实将它们放在了堆栈上。
Your code doesn't allocate a string on the stack. It allocates a
char*
on the stack, that is to say a pointer, and it makes that pointer point at a string literal. Attempting to modify the string literal is undefined behavior.To allocate the string on the stack, do:
Now you've taken a copy of the string literal in your stack-allocated array
arr
, and you're allowed to modify that copy.For full pedantry: everything I've described as "stack-allocated" are technically "automatic variables". C itself doesn't care where they're allocated, but I can guess with a lot of confidence that your implementation in fact does put them on a stack.
"abc"
没有在堆栈上分配,它是一个字符串文字。不,您无法修改它。您的编译器可以将该字符串放入只读内存段中(如果您的实现有这样的概念)。尝试改变它会导致未定义的行为。
(例如,它在使用默认编译选项的 GCC 的 Linux 上崩溃。)
"abc"
is not allocated on the stack, it is a string literal.No, you can't modify it. Your compiler can put that string in a read-only memory segment (if your implementation has such a concept). Trying to change it leads to undefined behavior.
(It crashes on Linux with GCC with default compile options for instance.)