[英]Global variables memory allocation in C++
我有以下测试代码:
#include <thread>
#include <cstdint>
#include <cstdlib>
int32_t global_buffer[1024][1024][256];
int main()
{
std::this_thread::sleep_for(std::chrono::seconds(5));
for (size_t i = 0; i < 1024; ++i)
for (size_t j = 0; j < 1024; ++j)
for (size_t k = 0; k < 256; ++k)
global_buffer[i][j][k] = rand();
std::this_thread::sleep_for(std::chrono::seconds(5));
int32_t* heap_buffer = new int32_t[1024 * 1024 * 256];
for (size_t i = 0; i < 1024 * 1024 * 256; ++i)
heap_buffer[i] = rand();
std::this_thread::sleep_for(std::chrono::seconds(5));
delete[] heap_buffer;
std::this_thread::sleep_for(std::chrono::seconds(5));
}
如果我在Windows 7上运行32位VS2013编译的程序,则我将具有以下内存行为:
我不明白为什么1.和2.会发生,所以我有几个问题:
3.7.1静态存储期限
所有没有动态存储持续时间,没有线程存储持续时间并且不是本地变量的变量都具有静态存储持续时间。 这些实体的存储应在程序期间持续进行
3.6.2非局部变量的初始化
有两大类命名的非局部变量:具有静态存储持续时间(3.7.1)的变量和具有线程存储持续时间(3.7.2)的变量。 具有静态存储持续时间的非局部变量将由于程序启动而初始化。 具有线程存储持续时间的非局部变量由于线程执行而被初始化。 在初始化的每个阶段中,初始化发生如下。
在进行任何其他初始化之前,应将具有静态存储持续时间(3.7.1)或线程存储持续时间(3.7.2)的变量进行零初始化(8.5)。
是否按需分配用于全局变量的内存?
链接器仅在二进制文件中存储初始化的数据。 运行时链接程序会在运行时为具有静态存储持续时间的未初始化数据分配空间,即使这样,也只有在您开始访问该数据时才提交物理内存。 有关更多详细信息,请参见数据段 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.