7

我想准确了解全局变量在我的程序中的存储位置。在堆栈上?在堆上?别的地方?

所以为此我写了这个小代码:

int global_vector[1000000];
int main () {
    global_vector[0] = 1; // just to avoid a compilation warning
    while(true); // to give me time to check the amount of RAM used by my program
    return 0;
}

无论我做多大global_vector,该程序只使用非常少量的 RAM。我不明白这是为什么。有人可以解释一下吗?

4

3 回答 3

11

这完全取决于实现,但通常全局变量存储在与堆栈和堆分开的特殊内存段中。该内存可以作为可执行文件本身内部的固定大小缓冲区分配,也可以分配在操作系统启动时分配给程序的段中。

您没有看到内存使用量上升的原因可能与操作系统如何处理虚拟内存有关。作为优化,除非您实际使用它,否则操作系统实际上不会为该巨型阵列的程序提供任何内存。尝试将程序更改为对数组的全部内容进行 for 循环,看看这是否会导致 RAM 使用率上升。(编译器中的优化器也有可能正在消除巨大的数组,因为它几乎完全未被使用。放置一个循环来读取/写入所有值也可能会迫使编译器保留它)。

希望这可以帮助!

于 2012-08-27T20:18:59.967 回答
5

优化器可能会完全删除数组,因为您从不使用它。

于 2012-08-27T20:18:31.307 回答
4

没有给定显式初始化程序的全局变量(例如本例中的您的变量)默认初始化为 0。它们被放置在称为.bss 段的内存区域中,并且没有额外的数据存储在目标文件/可执行文件中,指示数据的初始值(与显式初始化的数据不同,它的初始值必须存储在某处) .

When the OS loads the program, it reads in the descriptions of all of the segments and allocates memory for that. Since it knows that the .bss segment is initialized to all 0's, it can do a sneaky trick to avoid having to actually allocate tons of memory and then initialize it to all 0's: it allocates address space for the segment in the process's page table, but all of the pages point to the same page, filled with 0's.

That single zero-page is also set to read-only. Then, if and when the process writes to some data in the .bss segment, a page fault occurs. The OS intercepts the page fault, figures out what's going on, and then actually allocates unique memory for that page of data. It then restarts the instruction, and the code continues on its merry way as if the memory had been allocated all along.

So, the end result is that if you have a zero-initialized global variable or array, each page-sized chunk of data (typically 4 KB) that never gets written to will never actually have memory allocated for it.

Note: I'm being a little fuzzy here with the word "allocated". If you dig into this sort of thing, you're likely to encounter words such as "reserved" and "committed". See this question and this page for more info on those terms in the context of Windows.

于 2012-08-27T20:34:28.360 回答