c - 字符串文字在内存中的什么位置?栈/堆?

标签 c pointers char heap-memory stack-memory

<分区>

Possible Duplicate:
C String literals: Where do they go?

据我所知,

generally, pointer have to be allocated by malloc(), and will be allocated to heap, then unallocated by free();

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 会分配到哪里?栈还是堆?

最佳答案

字符串 literal 将被分配到 data segment 中。指向它的指针 a 将分配在堆栈上。

你的代码最终会被编译器转换成这样的东西:

#include <stdio.h>

const static char literal_constant_34562[7] = {'t', 'e', 's', 'a', 'j', 'a', '\0'};

int main()
{
    char *a;

    a = &literal_constant_34562[0];

    return 0;
}

因此,您问题的确切答案是:都不是堆栈数据bss 都是内存的不同区域。常量静态初始化变量将在数据中。

关于c - 字符串文字在内存中的什么位置?栈/堆?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4970823/

相关文章:

将字符串转换为 double

c - 通过 R 在 C 中操作矩阵

objective-c - 检查 Directory 是否是 OSX 中 Objective C 中的挂载点

c - 函数中指针的值

c++ - 如何正确使用vector<uint8_t>.data()?

c - 如何使用C编程将文本文件从服务器发送到客户端

c++ - 有没有办法拥有一个 bitbucket 指针/C++)

C++从文件中读取数据到char *

c++ - 如何从 char16_t 字符串文字中读取 double 值?

c - 从命令行获取输入?