Virtual Memory & Memory Mapping

demand paging

Demand paging is the policy of not bringing a page into RAM until the moment it is first actually used — load on demand, not in advance. It is like a hotel that does not make up a room until a guest is about to walk in: why prepare what nobody has asked for yet? This is why a program can start instantly and allocate gigabytes that cost almost nothing until touched.

Here is how it works, step by step. When the OS sets up a program or grants a big allocation, it does not copy the bytes into RAM; it just marks the pages not-present in the page table, recording where the real content lives (a file on disk, or 'all zeros'). The program runs and, the first time it reads or writes one of those pages, the MMU sees the not-present bit and raises a page fault. The OS catches it, finds a free frame, fills the frame with the right content (read from the executable, read from disk, or zero-filled for fresh memory), fixes the page-table entry to present, and restarts the instruction. From then on that page is resident and fast; pages never touched are never loaded at all.

The payoff is huge: faster startup (only the code actually run is paged in), lower memory use (untouched allocations cost nothing), and the ability to run programs larger than they will ever need resident. The honest caveat is timing: the cost of loading is paid at first touch, as a page fault, scattered through the run rather than up front. If those first-touch faults need disk reads (major faults) they can make the early part of a workload feel sluggish.

char *p = malloc(100 * 1024 * 1024); returns instantly and uses almost no physical RAM. Only when your loop writes into successive pages does each one fault in, one 4 KiB page at a time, so RAM use climbs gradually as you actually touch the memory.

Allocation is cheap; the cost arrives at first touch.

This is why a successful malloc() does not guarantee the memory is really there yet — the pages are promised, not committed. On systems with memory overcommit, the shortfall can surface much later, as a fault that fails or the OOM killer, not at the malloc() call.

Also called
lazy loading of pagesdemand-zero paging按需分頁