Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I able to allocate more memory to an array than my computer actually has

I am able to successfully run the code:

char* p = new char[34493878088];
cout << "Success at " << 34493878088 << " bytes" << endl;
delete[] p;

which as I understand allocates a 34 gigabyte char array. However, my computer only has 16 gigabytes of ram and my pagefile is only 3 gigabytes so how is this possible?

like image 624
Vityou Avatar asked Jun 29 '20 06:06

Vityou


1 Answers

The reserved address space ("virtual memory") is not mapped immediately into the physical memory. This is delayed till the memory is accessed.

When you first time access the memory location, a page fault interrupt initially happens, and only then the kernel configures the memory controller (that is a piece of hardware, part of CPU) to place a page of physical memory for your program at that address location. The program is then resumed from where it was interrupted and does not see these things happening.

A region in address space that is formally reserved but never accessed does not use the actual physical memory and can be larger than the amount of the physical memory available.

like image 183
Audrius Meškauskas Avatar answered Nov 07 '22 12:11

Audrius Meškauskas