What is virtual memory, and how does demand paging work?
MediumConceptVirtual Memory & Paging
Answer
Virtual memory lets each process use an address space larger than the physical RAM. Only the pages in use are kept in RAM; the rest stay on disk in a swap area (swap space on Linux, the page file on Windows). With demand paging, a page is loaded only when it is first accessed, not when the program starts.
- Each page-table entry has a valid-invalid bit: valid means the page is in RAM, invalid means it is on disk or not part of the process. Touching an invalid page raises a page fault, and the OS loads the page.
- Benefits: programs larger than RAM can run, more processes fit in memory, and programs start faster.
- It works because of locality of reference: over any short period, a program touches only a few of its pages.
- The cost is speed: a disk access takes milliseconds while RAM takes about 100 nanoseconds, so page faults must be rare.
Example: a laptop with 8 GB of RAM runs a browser (5 GB), an IDE (3 GB) and a game (4 GB), 12 GB in total. Only the pages each program is actively using stay in RAM. Idle parts, such as background tabs, wait in swap until touched again, and the game starts after loading only the pages its first level needs.