Virtual Memory & Demand Paging

swap space

Think of a small art studio where only a few canvases fit on the easels at once, and a big storage room down the hall for everything else. When you need a canvas that is in storage, you fetch it; when an easel is needed and all are full, you carry one back to storage. The storage room is the swap space: the area on disk where the OS keeps pages of process memory that do not currently fit in RAM, ready to be brought back when they are referenced again.

Concretely, swap space (also called the backing store) is a region of disk or SSD set aside to hold the contents of memory pages that are not resident in physical RAM. It is the 'somewhere else' that virtual memory relies on. There are two main kinds of page on it. Anonymous pages — a process's heap and stack, which have no file behind them — must be written to swap space when they are evicted, because there is nowhere else to put them. File-backed pages — code from an executable, or a memory-mapped file — usually do not need swap: a clean copy already exists in the original file, so the OS can just discard the frame and reload from the file later. Swap space can be a dedicated partition or a regular file; the OS tracks where each swapped-out page lives so it can find it on the next fault.

Why it matters: swap space is what physically realizes the illusion that memory is bigger than RAM — without a backing store there would be nowhere to put pages that do not fit, and the system could only hold what RAM can hold. It also acts as a safety valve under memory pressure, letting the system survive a temporary spike by pushing idle pages out. The honest caveats: swap is on disk, so heavy swapping is slow, and a system forced to swap constantly is thrashing, which feels like the machine has frozen. Swap is not 'extra fast memory' — it is a slow overflow area, useful precisely because it is rarely touched when working sets fit.

Under memory pressure the OS picks an idle 4 KB heap page (anonymous, dirty), writes it to the swap partition, and frees its frame for a more urgent page. Later, when the owner touches that heap page again, a page fault reads it back from swap.

Anonymous pages go to swap; clean file-backed pages can just be discarded.

Not every evicted page is written to swap. A clean, file-backed page (unmodified code, or an unwritten mapped page) can be dropped for free and reloaded from its file — only dirty or anonymous pages must actually be written out, which is why the dirty bit saves so much disk traffic.

Also called
backing storeswap areapaging file對換空間頁面檔