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

发布于 2024-10-17 08:56:27 字数 542 浏览 1 评论 0原文

可能的重复:
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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

伴随着你 2024-10-24 08:56:27

字符串 literal 将分配在 数据段。指向它的指针 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都是不同的内存区域。 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:

#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;
}

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.

秋意浓 2024-10-24 08:56:27

a 本身(指针)使用 auto 存储类(隐式)定义为局部变量,因此它分配在堆栈上(或实现用于堆栈的任何内存) -类似分配——某些机器,例如 IBM 大型机和第一个 Crays,没有正常意义上的“堆栈”)。

字符串文字“tesaja”是静态分配的。确切的位置取决于实现——有些将其与其他数据放在一起,有些将其放在只读数据段中。有些将所有数据视为读/写,将所有代码视为只读。由于他们希望字符串文字是只读的,因此他们将其放入代码段中。

a itself (the pointer) is defined as a local variable (implicitly) using the auto 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文