Memory Management in OS Paging, Segmentation: Tutorial, Examples, FAQs & Interview Tips
Logical vs Physical Address
The Memory Management Unit (MMU) is hardware that translates logical addresses to physical addresses at runtime.
| Feature |
Logical Address |
Physical Address |
| Also called |
Virtual address |
Real address |
| Generated by |
CPU during program execution |
Memory unit (RAM) |
| Visible to |
User/program |
Hardware only |
| Translation |
Translated to physical by MMU |
Actual location in RAM |
Address Binding
The process of mapping logical addresses to physical addresses can happen at different times:
- Compile Time: If the memory location is known at compile time, absolute code is generated. Must recompile if location changes.
- Load Time: If the memory location is not known at compile time, relocatable code is generated. Binding happens when the program is loaded into memory.
- Execution Time: Binding is delayed until runtime. Allows the process to be moved during execution. Requires hardware support (MMU). Used by most modern OS.
Contiguous Memory Allocation
Each process occupies a single contiguous block of memory.
Allocation Strategies:
- Fixed Partitioning: Memory is divided into fixed-size partitions. Simple but causes internal fragmentation (wasted space within a partition).
- Variable Partitioning: Partitions are created dynamically based on process size. Causes external fragmentation (free memory scattered in small pieces).
- First Fit: Allocate the first hole that is big enough. Fast.
- Best Fit: Allocate the smallest hole that is big enough. Minimizes wasted space but slow.
- Worst Fit: Allocate the largest hole. Leaves large remaining holes.
Fragmentation
- Internal Fragmentation: Wasted space inside an allocated partition. Occurs when a process is smaller than the partition it's allocated to.
- External Fragmentation: Total free memory is enough but not contiguous. Occurs in variable partitioning.
- Compaction: Shuffle memory contents to consolidate free space. Expensive - requires moving all processes.
Paging
Paging eliminates external fragmentation by dividing both physical memory and logical memory into fixed-size blocks:
- Frame: Fixed-size block of physical memory
- Page: Fixed-size block of logical memory (same size as frame)
- The OS maintains a page table for each process that maps page numbers to frame numbers
- Logical address = (page number, offset); Physical address = (frame number, offset)
- Eliminates external fragmentation but causes internal fragmentation (last page may not be full)
Segmentation
Segmentation divides a program into logical units (segments) of variable size - code segment, data segment, stack segment, heap segment.
- Each segment has a name and length
- Logical address = (segment number, offset)
- OS maintains a segment table with base address and limit for each segment
- Supports user's view of memory (logical units)
- Causes external fragmentation