C++ 中堆栈或堆中的全局内存管理?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1169858/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 19:05:42  来源:igfitidea点击:

Global memory management in C++ in stack or heap?

c++memory-managementstack

提问by sameer karjatkar

If I declare a data structure globally in a C++ application , does it consume stack memory or heap memory ?

如果我在 C++ 应用程序中全局声明一个数据结构,它会消耗堆栈内存还是堆内存?

For eg

例如

struct AAA
{

.../.../.
../../..
}arr[59652323];

回答by Milan

Since I wasn't satisfied with the answers, and hope that the sameer karjatkar wants to learn more than just a simple yes/no answer, here you go.

由于我对答案不满意,并希望相同的 karjatkar 想要了解的不仅仅是简单的是/否答案,所以你去吧。

Typically a process has 5 different areas of memory allocated

通常,一个进程分配了 5 个不同的内存区域

  1. Code - text segment
  2. Initialized data – data segment
  3. Uninitialized data – bss segment
  4. Heap
  5. Stack
  1. 代码 - 文本段
  2. 初始化数据——数据段
  3. 未初始化的数据——bss 段

If you really want to learn what is saved where then read and bookmark these:

如果您真的想了解保存在何处的内容,请阅读以下内容并添加书签:

COMPILER, ASSEMBLER, LINKER AND LOADER: A BRIEF STORY(look at Table w.5)

编译器、汇编器、链接器和加载器:简要故事(见表 w.5)

Anatomy of a Program in Memory

内存中的程序剖析

alt text

替代文字

回答by Charlie Martin

The problem here is the question. Let's assume you've got a tiny C(++ as well, they handle this the same way) program like this:

这里的问题是问题。让我们假设你有一个像这样的小 C(++,他们也以同样的方式处理) 程序:

/* my.c */

char * str = "Your dog has fleas.";  /* 1 */
char * buf0 ;                         /* 2 */

int main(){
    char * str2 = "Don't make fun of my dog." ;  /* 3 */
    static char * str3 = str;         /* 4 */
    char * buf1 ;                     /* 5 */
    buf0 = malloc(BUFSIZ);            /* 6 */
    buf1 = malloc(BUFSIZ);            /* 7 */

    return 0;
}
  1. This is neither allocated on the stack NOR on the heap. Instead, it's allocated as static data, and put into its own memory segment on most modern machines. The actual stringis also being allocated as static data and put into a read-only segment in right-thinking machines.
  2. is simply a static allocated pointer; room for one address, in static data.
  3. has the pointer allocated on the stackand will be effectively deallocated when mainreturns. The string, since it's a constant, is allocated in static data space along with the other strings.
  4. is actually allocated exactly like at 2. The statickeyword tells you that it's not to be allocated on the stack.
  5. ...but buf1is on the stack, and
  6. ... the malloc'ed buffer space is on the heap.
  7. And by the way., kids don't try this at home. mallochas a return value of interest; you should alwayscheck the return value.
  1. 这既不在堆栈上也不在堆上分配。相反,它被分配为静态数据,并在大多数现代机器上放入自己的内存段。实际的字符串也被分配为静态数据,并放入思维正常的机器中的只读段中。
  2. 只是一个静态分配的指针;一个地址的空间,在静态数据中。
  3. 将指针分配在堆栈上,并在main返回时有效地释放。由于字符串是常量,因此它与其他字符串一起分配在静态数据空间中。
  4. 实际上与 2 完全一样分配。static关键字告诉您它不会在堆栈上分配。
  5. ...但是buf1在堆栈上,并且
  6. ... malloc 的缓冲区空间在堆上。
  7. 顺便说一句,孩子们不要在家里尝试这个。 malloc有利息的回报值;您应该始终检查返回值。

For example:

例如:

char * bfr;
if((bfr = malloc(SIZE)) == NULL){
   /* malloc failed OMG */
   exit(-1);
}

回答by Tomek Kopczuk

Usually it consumes neither. It tries to allocate them in a memory segment which is likely to remain constant-size for the program execution. It might be bss, stack, heap or data.

通常它都不消耗。它尝试将它们分配在一个内存段中,该段可能为程序执行保持恒定大小。它可能是 bss、堆栈、堆或数据。

回答by EFraim

Neither. It is .data section.

两者都不。它是 .data 部分。

回答by Philippe Leybaert

Global memory is pre-allocated in a fixed memory block, or on the heap, depending on how it is allocated by your application:

全局内存预先分配在固定内存块或堆上,具体取决于您的应用程序如何分配:

byte x[10]; // pre-allocated by the compiler in some fixed memory block
byte *y

main()
{
   y = malloc(10); // allocated on the heap
}

EDIT:

编辑

The question is confusing: If I allocate a data structure globally in a C++ application , does it consume stack memory or heap memory ?

问题令人困惑:如果我在 C++ 应用程序中全局分配数据结构,它会消耗堆栈内存还是堆内存?

"allocate"? That could mean many things, including calling malloc(). It would have been different if the question was "if I declare and initialize a data structure globally".

“分配”?这可能意味着很多事情,包括调用 malloc()。如果问题是“如果我全局声明和初始化一个数据结构”,情况会有所不同。

Many years ago, when CPUs were still using 64K segments, some compilers were smart enough to dynamically allocate memory from the heap instead of reserving a block in the .data segment (because of limitations in the memory architecture).

许多年前,当 CPU 仍在使用 64K 段时,一些编译器足够聪明,可以从堆中动态分配内存,而不是在 .data 段中保留一个块(因为内存架构的限制)。

I guess I'm just too old....

我想我只是太老了......

回答by DML

Neither declaring a data structure globally in a C++ consumes heap or stack memory. Actually, global variables are typically allocated in a data segment whose size remains unchanged during the whole program. Stacks and heaps are typically used for variables that get created and destroyed during executing the program.

在 C++ 中全局声明数据结构都不消耗堆或堆栈内存。实际上,全局变量通常分配在一个数据段中,该数据段在整个程序中保持不变。堆栈和堆通常用于在执行程序期间创建和销毁的变量。

Program Memory Space

程序存储空间

回答by Rudi Bierach

The global object itself will take up memory that the runtime or compiler reserves for it before main is executed, this is not a variable runtime cost so neither stack nor heap.

全局对象本身将占用运行时或编译器在执行 main 之前为其保留的内存,这不是可变的运行时成本,因此既不是堆栈也不是堆。

If the ctor of the object allocates memory it will be in the heap, and any subsequent allocations by the object will be heap allocations.

如果对象的 ctor 分配内存,它将在堆中,并且对象的任何后续分配都将是堆分配。

It depends on the exact nature of the global object, if it's a pointer or the whole object itself that is global.

它取决于全局对象的确切性质,如果它是一个指针或整个对象本身是全局的。

回答by user128026

global variables live on the heap. these are a special case because they live for the life of the program

全局变量存在于堆中。这些是一个特例,因为它们是为程序的生命周期而存在的

回答by srnayak

If you are explicitly allocating the memory yourself by new or malloc, then it will be allocated in heap. If the compiler is allocating the memory, then it will be allocated on stack.

如果您自己通过 new 或 malloc 显式分配内存,那么它将在堆中分配。如果编译器正在分配内存,那么它将在堆栈上分配。