字符串文字在内存中的什么位置?堆栈/堆?
可能的重复:
C 字符串文字:它们去哪里?
据我所知,
一般来说,指针必须是 由malloc()分配,并且将被分配 到堆,然后通过 free() 取消分配;
和
非指针(int、char、float 等)将是 自动分配到堆栈,并且 只要函数转到就未分配 返回
但是,从以下代码来看:
#include <stdio.h>
int main()
{
char *a;
a = "tesaja";
return 0;
}
a
将分配到哪里?栈还是堆?
Possible Duplicate:
C String literals: Where do they go?
As far as I know,
generally, pointer have to be
allocated by malloc(), and will be allocated
to heap, then unallocated by free();
and
non pointer(int,char,float,etc..) will be
allocated automatically to stack, and
unallocated as long as the function go to
return
but, from following code :
#include <stdio.h>
int main()
{
char *a;
a = "tesaja";
return 0;
}
where will a
allocated to ? stack or heap ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
字符串 literal 将分配在 数据段。指向它的指针
a
将在堆栈上分配。您的代码最终会被编译器转换成如下所示:
因此,您问题的确切答案是:都不是。 堆栈、数据、bss和堆都是不同的内存区域。 Const 静态初始化变量将位于数据中。
The string literal will be allocated in data segment. The pointer to it,
a
, will be allocated on the stack.Your code will eventually get transformed by the compiler into something like this:
Therefore, the exact answer to your question is: neither. Stack, data, bss and heap are all different regions of memory. Const static initialized variables will be in data.
a
本身(指针)使用auto
存储类(隐式)定义为局部变量,因此它分配在堆栈上(或实现用于堆栈的任何内存) -类似分配——某些机器,例如 IBM 大型机和第一个 Crays,没有正常意义上的“堆栈”)。字符串文字“tesaja”是静态分配的。确切的位置取决于实现——有些将其与其他数据放在一起,有些将其放在只读数据段中。有些将所有数据视为读/写,将所有代码视为只读。由于他们希望字符串文字是只读的,因此他们将其放入代码段中。
a
itself (the pointer) is defined as a local variable (implicitly) using theauto
storage class, so it's allocated on the stack (or whatever memory the implementation uses for stack-like allocation -- some machines, such as IBM mainframes and the first Crays, don't have a "stack" in the normal sense).The string literal "tesaja" is allocated statically. Exactly where that will be depends on the implementation -- some put it with other data, and some put it in a read-only data segment. A few treat all data as read/write and all code as read-only. Since they want they string literal to be read-only, they put it in the code segment.