内存中的字符串文字在哪里?堆栈/堆? [英] Where in memory are string literals ? stack / heap?
问题描述
可能重复:
C 字符串文字:它们去哪儿了?
据我所知
一般来说,指针必须是由 malloc() 分配,并将被分配堆,然后由 free() 取消分配;
generally, pointer have to be allocated by malloc(), and will be allocated to heap, then unallocated by free();
和
非指针(int,char,float,etc..) 将是自动分配给堆栈,并且未分配,只要函数转到返回
non pointer(int,char,float,etc..) will be allocated automatically to stack, and unallocated as long as the function go to return
但是,从以下代码:
#include <stdio.h>
int main()
{
char *a;
a = "tesaja";
return 0;
}
a
将分配到哪里?堆栈还是堆?
where will a
allocated to ? stack or heap ?
推荐答案
字符串 literal 将分配在数据段中.指向它的指针 a
将在堆栈上分配.
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:
#include <stdio.h>
const static char literal_constant_34562[7] = {'t', 'e', 's', 'a', 'j', 'a', ' '};
int main()
{
char *a;
a = &literal_constant_34562[0];
return 0;
}
因此,您的问题的确切答案是:都不是.Stack、data、bss 和 heap 都是不同的内存区域.const 静态初始化变量将在 data 中.
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.
这篇关于内存中的字符串文字在哪里?堆栈/堆?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!