Notes › Memory Management
Memory Management

Memory Management Notes

Visual guide to Address Translation, Paging, Virtual Memory, Page Faults, and Replacement Policies.

Logical vs Physical Addresses

Address Binding
The CPU generates **Logical Addresses** (also called virtual addresses). RAM only understands **Physical Addresses** (locations on memory chips).

Memory Management Unit (MMU): A hardware chip that performs runtime mapping from logical addresses to physical addresses using base, limit, or page tables.

Paging & Segmentation

Paging vs Segmentation
Operating Systems solve the **External Fragmentation** problem (wasted gaps in memory) by breaking physical memory into fixed blocks.

Paging: - Breaks physical memory into fixed-sized blocks called **Frames**. - Breaks logical memory into blocks of the same size called **Pages**. - No external fragmentation, but can cause **Internal Fragmentation** (wasted bytes in the last allocated page). - Address structure: **Page Number (p)** (index in page table) + **Offset (d)** (distance from page start).

Segmentation: - Logical segments of variable lengths corresponding to code functions, stack, variables. - Avoids internal fragmentation but suffers from external fragmentation as segments are allocated/freed.
Memory Trick: Think of Paging like buying *sliced bread* (every slice is exactly the same thickness). Segmentation is like carving *slices of cake* of different sizes based on who wants how much.

Virtual Memory & Page Faults

Page Fault Lifecycle
**Virtual Memory** allows executing programs that are larger than physical memory by loading pages into RAM only when referenced (**Demand Paging**).

If a program references a page not present in RAM (indicated by an **Invalid Bit** in the page table), a **Page Fault** occurs.

How the OS handles a Page Fault:
  1. Trap to the OS kernel.
  2. Save the current process state and registers.
  3. Locate the target page on the hard disk/SSD.
  4. Find a free physical frame in RAM. (If none, perform a page replacement).
  5. Read the page from disk into the frame.
  6. Update page table entry (set bit to valid).
  7. Resume the process at the instruction that caused the fault.

Page Replacement Algorithms

Algorithm How It Works Pros / Cons Belady's Anomaly?
FIFO Replaces the oldest page in memory. Simple to implement. Wastes frames; suffers from Belady's Anomaly. Yes
LRU Replaces the page not referenced for the longest time. Excellent performance, stack algorithm. Hard to implement in hardware. No
Optimal (OPT) Replaces page that will not be used for longest time in future. Guarantees lowest possible fault rate. Impossible to build (requires future knowledge). No
Belady's Anomaly: More memory frames can sometimes lead to *more* page faults in FIFO replacement. (Example: 1,2,3,4,1,2,5,1,2,3,4,5 reference string shows more faults with 4 frames than with 3 frames!).
Practice Now