简体   繁体   中英

Global variables memory allocation in C++

I have this test code:

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

If I run the program, compiled with VS2013 on 32bits, on Windows 7 I have the following memory behavior:

  1. memory usage is very low, several KB in the first ~5 seconds
  2. memory usage increases in time until it hits ~1 GB
  3. memory usage stays ~1 GB for 5 seconds
  4. memory usage jumps to ~2 GB and stays there for ~5 second
  5. memory usage jumps to ~1 GB

As I don't understand why 1. and 2. are happening I have several questions:

  1. Why doesn't the program start with ~1 GB memory usage?
  2. Is memory for global variables allocated on demand?
  3. Is this a VS/Windows specific behavior or other compilers/OS have the same behavior?
  4. Is this behavior correct? The std says:

3.7.1 Static storage duration

All variables which do not have dynamic storage duration, do not have thread storage duration, and are not local have static storage duration. The storage for these entities shall last for the duration of the program

3.6.2 Initialization of non-local variables

  1. There are two broad classes of named non-local variables: those with static storage duration (3.7.1) and those with thread storage duration (3.7.2). Non-local variables with static storage duration are initialized as a consequence of program initiation. Non-local variables with thread storage duration are initialized as a consequence of thread execution. Within each of these phases of initiation, initialization occurs as follows.

  2. Variables with static storage duration (3.7.1) or thread storage duration (3.7.2) shall be zero-initialized (8.5) before any other initialization takes place.

Is memory for global variables allocated on demand?

Linkers store only initialized data in the binaries. Space for uninitialized data with static storage duration is allocated at run-time by the run-time linker, and even then the physical memory is committed only when you start accessing that data. See data segment for more details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM