Virtual Memory

Overview

Virtual memory is a memory management technique that provides an abstraction of the physical RAM, giving each process the illusion that it has a large, contiguous block of memory, regardless of the actual physical layout.

Core Concepts

  • Logical vs. Physical Address:
    • Logical Address: Generated by the CPU; the address a program “sees”.
    • Physical Address: The actual location in the physical RAM chips.
  • Paging:
    • Pages: Fixed-size blocks of logical memory.
    • Frames: Fixed-size blocks of physical memory.
    • Page Table: A map that translates logical pages to physical frames.
  • Segmentation: Dividing memory into logical segments (e.g., code, data, stack) of varying sizes.
  • Demand Paging: Loading pages into RAM only when they are actually accessed, rather than loading the entire program at start.
  • Thrashing: A state where the OS spends more time swapping pages between RAM and disk than executing instructions, causing the system to crawl.
  • Page Replacement Algorithms:
    • FIFO: First-In, First-Out.
    • LRU (Least Recently Used): Replaces the page that hasn’t been used for the longest time.
    • Optimal: Theoretically best, but requires knowing the future.

Code Examples

# Conceptual view of paging via system tools
# On Linux, you can check swap usage and memory pressure
free -m
vmstat 1

Use Cases

  • Running Large Programs: Allowing a program to run even if its size exceeds the physical RAM available.
  • Isolation: Ensuring one process cannot access the memory of another process, increasing security and stability.
  • Memory Efficiency: Sharing read-only code segments (libraries) between different processes.

Gotchas

  • Latency: Accessing a page from the disk (swap) is orders of magnitude slower than accessing RAM.
  • Internal Fragmentation: Wasting space within a page if the process doesn’t use the entire page.

Related Notes