Reputation: 19
I created the following functions to check the memory usage of static local variables and expected the array to take up roughly 5MB of memory but when I ran it the physical memory usage of the process was merely 0,2MB and went up when I actually set a value to each element in the array.
My understanding was that the array would be allocated memory when I first initialized it regardless of the values of elements in it. As I am able to access the first and the last element of the array where did the memory go inbetween?
void func() {
static char a[5000000];
a[0] = 'a';
a[4999999] = 'a';
cin >> a;
}
int main(int argc, char const *argv[]) {
func();
return 0;
}
Upvotes: 1
Views: 239
Reputation: 8475
This is due to lazy memory allocation or zero fill on demand, as explained below.
This is is explained in zero initialization at cppreference:
Zero initialization is performed in the following situations:
1 For every named variable with static or thread-local storage duration that is not subject to constant initialization (since C++14), before any other initialization.
So this variable qualifies. What does it mean zero initialization:
The effects of zero initialization are:
- If T is a scalar type, the object's initial value is the integral constant zero explicitly converted to T.
- [...] If T is array type, each element is zero-initialized
As an optimization, most modern systems don't even allocate any memory for zero initialized global/static variables, and that's why array size does not affect memory usage. What happens instead, the executable has a mark that says: "here should be zero values", and nothing more. When the program loads, all the addresses map to a small and shared read-only block of physical RAM that contains zeros.
Several virtual addresses can map to the same memory through a piece of hardware in the CPU which is called a "Memory management unit" (MMU). When the code attempts to write to the an address in the range, the MMU notifies the operating system (OS) that someone is writing a read-only block of memory, and the OS allocates the memory only then
Upvotes: 1