What is virtual memory and why is it used?
Short answer: Virtual memory gives every process its own private address space. The program uses virtual addresses, and the MMU translates each one to a physical address through page tables set up by the OS. This provides isolation between processes, lets the OS use physical memory flexibly (scattered pages, only what is used, swapping), and makes sharing and memory-mapped files easy.
Benefits
- Isolation and protection: a process cannot read or write another process's memory or the kernel's; each page has permissions (read, write, execute, user/kernel).
- Contiguous view of scattered memory: a 100 MB array looks contiguous to the program even though its physical pages are spread across RAM.
- Demand paging and overcommit: pages get physical frames only when first touched. A process can reserve a large heap and use a little of it.
- Swapping: rarely used pages can be moved to disk to free RAM.
- Sharing: shared libraries and the kernel are mapped into many processes but stored once;
fork()uses copy-on-write. - Memory-mapped files and devices:
mmap()maps a file or device memory into the address space so it can be accessed with normal loads and stores.
Typical 64-bit Linux process layout (low to high)
0x0000... (unmapped: catches NULL pointer accesses)
text program code, read-only + execute
data, bss global/static variables
heap ↑ malloc() (brk / mmap)
... shared libraries, mmap regions
stack ↓ grows down, with a guard page
0x0000ffff... end of user space (ARM64 with 48-bit VA)
kernel space not accessible from user mode
Address translation in one line: virtual page number → page table lookup → physical frame number; the offset inside the page is unchanged. The TLB caches recent translations so most accesses do not need a table walk.
Costs: page table memory, TLB misses, page fault handling. Real-time systems sometimes lock memory (mlockall()) to avoid page faults during time-critical work.
Embedded contrast: a Cortex-M microcontroller has no MMU, so there is no virtual memory. All tasks share one physical address space, and an MPU can only restrict access to regions.