Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the C++ global variable not affect to memory usage of program

Tags:

c++

c

In my program I declare an initialized global variable (as an array). But it only affects the size of executable file, the memory usage by the program was not affected.

My program is like that

char arr[1014*1024*100] = {1};

int _tmain(int argc, _TCHAR* argv[])
{
    while (true)
    {

    }
    return 0;
}

Size of executable file is 118MB but memory usage when running program was only 0.3MB

Can anyone explain for me?

like image 650
TuanPM Avatar asked Dec 06 '22 15:12

TuanPM


2 Answers

Most operating systems used demand-paged virtual memory.

This means that when you load a program, the executable file for that program isn't allow loaded into memory immediately. Instead, virtual memory pages are set up to map the file to memory. When (and if) you actually refer to an address, that causes a page fault, which the OS then handles by reading the appropriate part of the file into physical memory, then letting the instruction re-execute.

In your case, you don't refer to arr, so the OS never pulls that data into memory.

If you were to look at the virtual address space used by your program (rather than the physical memory you're apparently now looking at), you'd probably see address space allocated for all of arr. The virtual address space isn't often very interesting or useful to examine though, so most things that tell you about memory usage will tell you only about the physical RAM being used to store actual data, not the virtual address space that's allocated but never used.

Even if you do refer to the data, the OS can be fairly clever: depending on how often you refer to the data (and whether you modify it), only part of the data may ever be loaded into RAM at any given time. If it's been modified, the modified portions can be written to the paging file to make room in RAM for data that's being used more often. If it's not modified, it can be discarded (because the original data can be re-loaded from the original file on disk whenever it's needed).

like image 52
Jerry Coffin Avatar answered Feb 16 '23 03:02

Jerry Coffin


The reason your memory in use while your executable is executing is significantly smaller than the space required on your hard-drive (or solid-state drive) to store the executable is because you're not pulling the array itself into memory.

In your program, you never access or call your array—let alone bring into memory all at once in parallel. Because of that, the memory needed to run your executable is incredibly small when compared to the size of the executable (which has to store your massively large array).

I hope that makes sense. The difference between the two is that one is executing and one is stored on your computer's internal disk. Something is only brought into execution when it's brought into memory.

like image 21
Bloo Avatar answered Feb 16 '23 03:02

Bloo