Skip to content

Memory Management (MMU · Fragmentation · Paging · Segmentation · Virtual Memory) ​

Memory management is the operating system's job of letting multiple processes share limited main memory safely and efficiently. It deals with which space to give to whom, how to stop processes from invading each other's space, and what to do when memory runs short.

At a Glance ​

  • Analogy: main memory is a desk in a library reading room, and the hard disk is the stacks. You can read quickly at the desk, but there are few seats; the stacks are huge, but fetching a book from there takes a long time.
  • The operating system is the reading room manager. It hands out a desk to each person (process), keeps people from touching others' desks, and when desks run short, sends books nobody is reading right now back to the stacks to make room.
  • How memory inside a single process is split into regions such as Stack and Heap was covered in Memory Layout. This article looks one level higher: how the operating system hands out memory to multiple processes.

Main Memory ​

Main memory (RAM) is the storage device the CPU can access directly. To run a program, it must first be loaded into memory.

  • Memory is a long line of bytes, each with an address.
  • The CPU goes to the address pointed to by a register (the program counter) and fetches the next instruction to execute.
  • If the data needed to execute an instruction is not in memory, it must first be brought from disk into memory. The hardware MMU notices that "the data is not in memory" and reports it (a page fault), and then the operating system fetches the data from disk.

Logical Address vs. Physical Address ​

TypeMeaningWho sees it
Logical address (virtual address)The address a program sees. Each process thinks its memory starts at address 0Program, CPU
Physical addressThe address on the actual RAM chipMemory hardware

When a program says "read address 100," that 100 is a logical address. In reality, it might be address 20,580 in RAM. The device that does this translation is the MMU.

MMU (Memory Management Unit) ​

The MMU is the hardware that translates logical addresses into physical addresses. It manages the CPU's memory access in general, including memory protection and cache management.

Because memory space is limited, the concept of virtual addresses was created to make it look as though users have more memory than they actually do. A virtual address is the address space seen from the program's point of view. Finding where the real data lives from a virtual address requires very fast address translation, and the MMU takes care of that.

Here is what having an MMU gives you.

  • Without an MMU, programs would have to access physical addresses directly, so each program would have to carefully avoid overlapping addresses with others.
  • It removes the hassle of users having to allocate storage locations one by one themselves.
  • It allows a process to run even if it is larger than the actual memory capacity. (Explained below in Virtual Memory.)

Also, going directly to slow main memory every time is inefficient for the CPU, so there is cache memory to bridge the speed gap between the two. That is also covered below.

Memory Protection by the MMU ​

Each process must have its own independent memory space and access only its own space. So each process is given a range of addresses it is allowed to access, and any attempt to go outside that range triggers a trap (an exception that notifies the operating system) and is blocked.

The simplest method uses a base register and a limit register.

  • base register: the physical address where the process starts in memory
  • limit register: the size of the process

The range of legal addresses x the process may access is:

text
base <= x < base + limit
text
Physical memory
┌──────────────────┐ 0
│ Operating system │
├──────────────────┤ 30000  ← base
│                  │
│   Process A      │  limit = 12000
│                  │
├──────────────────┤ 42000  (base + limit)
│   Process B      │  ← trap if A touches this
└──────────────────┘

In the figure below, base is 300040 and limit is 120900, so this process can only access addresses from 300040 up to (but not including) 420940 (300040 + 120900).

Setting one process's memory range with a base register of 300040 and a limit register of 120900

Image source: gyoogle tech interview notes, Memory

If the process goes outside this range, a trap occurs, and the operating system usually force-terminates the process. The Segmentation fault commonly seen on Linux is this case. For safety, the base and limit registers are designed so they can be changed only in kernel mode. If a user program could freely widen its own range, the protection would be meaningless.

Ways to Hand Out Memory ​

In a multiprogramming system that keeps multiple processes in memory at the same time, memory must be handed out to processes as needed (dynamically partitioned). There are two broad approaches.

ApproachMeaning
Contiguous allocationLoad the whole program into one continuous chunk of memory
Non-contiguous allocationSplit the program into pieces that can be loaded into separate places

Contiguous Memory Allocation ​

Fixed Partitioning ​

Memory is divided in advance into slots (partitions) of fixed size, and each slot holds one process.

  • Problem: if a process smaller than the slot goes in, leftover space remains inside the slot, and no other process can use it. This is called internal fragmentation.

Dynamic Partitioning (Variable Partitioning) ​

Instead of dividing slots in advance, each time a process arrives, memory is cut to exactly that size and given to it.

  • Problem: as processes repeatedly come and go, small empty spaces get scattered all over memory. The total free space is enough, but there is no single continuous chunk, so a new process cannot be loaded. This is called external fragmentation.

When there are several empty spaces, there are also ways to choose where to put a process.

MethodSelection rule
First FitScan from the start and take the first empty space that fits
Best FitThe smallest empty space that fits (minimizes leftover space)
Worst FitThe largest empty space (leaves a large leftover that is easy to reuse)

When external fragmentation gets severe, you can do compaction, pushing processes to one side to merge the empty spaces into one, but it is expensive because memory has to be moved wholesale.

Internal vs. External Fragmentation ​

Fragmentation is when free space or data in storage gets split into many pieces and cannot be used properly.

text
Internal fragmentation (space left over inside a slot)
┌──────────────────┐
│ Process (7KB)    │
│ ░░ 3KB unused ░░ │ ← only 7KB used in a 10KB slot, 3KB wasted
└──────────────────┘

External fragmentation (space scattered between slots)
┌──────┬────┬──────┬────┬──────┬────┐
│ P1   │ 2K │ P2   │ 3K │ P3   │ 2K │ ← total free space 7KB
└──────┴────┴──────┴────┴──────┴────┘
  A 6KB process can't fit because there is no continuous space
TypeWhere it occursTypical cause
Internal fragmentationInside allocated spaceFixed partitioning, paging
External fragmentationBetween allocated spacesDynamic partitioning, segmentation

Non-contiguous Memory Allocation ​

This approach splits a program into pieces and loads them into different places in memory. Let's start with the terms.

TermMeaning
PageA piece of a process cut to equal size
FrameA slot of main memory cut to the same size as a page
SegmentA piece of a process divided by meaning, such as code, data, and stack. Sizes differ, and each segment is loaded contiguously in memory

Cutting pieces to a fixed size is paging; cutting them to variable sizes is segmentation.

Paging ​

A process is cut into equal-sized pages, which are placed into any free frames in memory. Which page is in which frame is recorded in a page table that each process has.

text
Process (logical)        Page table             Physical memory
┌─────────┐            ┌──────┬──────┐        ┌─────────┐ Frame 0
│ Page 0  │ ─────────▶ │  0   │  5   │        ├─────────┤ Frame 1  ← Page 2
├─────────┤            │  1   │  9   │        ├─────────┤ ...
│ Page 1  │            │  2   │  1   │        ├─────────┤ Frame 5  ← Page 0
├─────────┤            └──────┴──────┘        ├─────────┤ ...
│ Page 2  │                                   ├─────────┤ Frame 9  ← Page 1
└─────────┘                                   └─────────┘

Translating an Address ​

A logical address can be split into a page number and an offset (which byte within the page). Here is a Python calculation where the page size is 4KB (4,096 bytes) and the page table matches the figure above.

python
PAGE_SIZE = 4096                     # page size 4KB
page_table = {0: 5, 1: 9, 2: 1}      # page number -> frame number

def translate(logical):
    page = logical // PAGE_SIZE      # which page
    offset = logical % PAGE_SIZE     # which byte within the page
    if page not in page_table:
        return f"Logical address {logical}: page {page} is not in memory -> page fault"
    frame = page_table[page]
    physical = frame * PAGE_SIZE + offset
    return f"Logical address {logical} = page {page}, offset {offset} -> frame {frame} -> physical address {physical}"

for addr in [100, 8200, 13000]:
    print(translate(addr))
text
Logical address 100 = page 0, offset 100 -> frame 5 -> physical address 20580
Logical address 8200 = page 2, offset 8 -> frame 1 -> physical address 4104
Logical address 13000: page 3 is not in memory -> page fault

This calculation is exactly what the MMU does. Reading the page table from memory every time would be slow, so it also uses the TLB (Translation Lookaside Buffer), a small cache that stores recently used translation results.

Fragmentation in Paging ​

  • Any page can go into any free frame, so there is no external fragmentation.
  • However, if the process size is not evenly divisible by the page size, empty space remains in the last page. A little internal fragmentation occurs.
python
import math
PAGE_SIZE = 4096
process_size = 10_000                  # process size 10,000 bytes
pages = math.ceil(process_size / PAGE_SIZE)
waste = pages * PAGE_SIZE - process_size
print(f"Pages needed: {pages}")
print(f"Space left in the last page (internal fragmentation): {waste} bytes")
text
Pages needed: 3
Space left in the last page (internal fragmentation): 2288 bytes

Segmentation ​

A process is divided into meaningful units (segments) such as code, data, stack, and heap. Each segment has a different size, and each segment's start address (base) and length (limit) are recorded in a segment table. It is like applying the base/limit protection seen earlier to each segment.

  • Allocation matches the segment size exactly, so there is no internal fragmentation.
  • It is good for setting protection and sharing by unit of meaning, such as "the code segment is read-only."
  • Unlike dynamic partitioning, the process is loaded as several segments instead of one big chunk, so memory is used more efficiently and management is easier.
  • However, as chunks of varying sizes come and go, external fragmentation occurs.

That is why real operating systems use paged segmentation, which further splits segments into pages, or, like Linux on today's x86-64 and ARM, effectively use paging only.

Virtual Memory ​

Virtual memory is a technique that runs a process by loading only the parts needed right now, instead of the whole process. The rest stays on disk and is brought in when needed. This lets you run programs larger than physical memory and keep more processes loaded at once.

  • Bringing in pages only when needed is called Demand Paging.
  • If a needed page is not in memory, a Page Fault occurs, and the operating system fetches the page from disk before continuing execution.

The left side of the figure below is the virtual memory seen by one process. To the process it looks like one continuous space, but in reality each piece is scattered across various places in RAM (avoiding other processes' memory), or is still on disk.

Pieces of a process's virtual memory mapped to various locations in physical RAM and on disk

Image source: Wikimedia Commons (Ehamberg, CC BY-SA 3.0)

Comparing Four Approaches ​

ApproachMust the whole thing be loaded?External fragmentationInternal fragmentationCharacteristics
Simple pagingYesNoneA littleSplit into equal-size pages and put in any frame
Simple segmentationYesYesNoneSplit by meaning, more efficient than dynamic partitioning
Virtual memory pagingNo (only needed pages)NoneA littleLoads automatically when needed; management is complex, so there is overhead
Virtual memory segmentationNo (only needed segments)YesNoneLoads automatically when needed; management is complex, so there is overhead

Swapping ​

Swapping means temporarily moving contents of memory out to the swap area on disk (swap out) and bringing them back into memory when needed (swap in).

  • The old approach swapped out an entire process at once.
  • Today's paging systems mostly swap out and in page by page.
  • If memory is so short that swapping happens nonstop, you get Thrashing: the CPU sits almost idle while only the disk is busy. This comes up again in Page Replacement Algorithms.

Over-allocating Memory ​

Over-allocation is a situation where more memory has been handed out to processes than the actual memory size. Thanks to virtual memory, the operating system can "pretend there is enough memory" without the user noticing.

But if things happen in the following order, the over-allocation is in danger of being exposed.

  1. A page fault occurs while a process is running
  2. The OS finds where on disk that page is
  3. It needs to load the page into a free frame in memory, but all frames are in use, so there is no free frame

There are two ways to create a free frame.

MethodDescriptionProblem
1. Terminate a processEnd one process in memory to free up spaceThe user program suddenly shuts down, so the user notices
2. Swap outMove a page in memory out to disk to free up spaceThe user doesn't notice

Paging is a method the operating system chose on its own to improve system efficiency, so it must handle this without the user noticing. That is why it solves it with option 2, page replacement. (When memory truly runs out, Linux eventually uses the OOM Killer, which corresponds to option 1. See Memory Leaks and OOM.)

Page Replacement ​

Page replacement means, when there is no free frame, choosing one page in memory (the victim) to evict and loading the needed page in its place.

  1. A page fault occurs while a process is running
  2. Find where on disk the needed page is
  3. Check whether there is a free frame in memory
    • If there is a free frame, use it
    • If not, choose a victim frame, write it to disk, and update the page table
  4. Load the needed page into the freed frame and update the page table
  5. Resume the process from the instruction where it stopped

After replacement, the process must keep running as if nothing happened. To do that, the overhead of replacement must be kept as low as possible.

Ways to Reduce Overhead ​

When there is no free frame, the disk is accessed twice: once to write the victim to disk, and once to read the needed page. If replacements are frequent, disk I/O piles up and things slow down badly.

Method 1: Use a modify bit (dirty bit)

Each page has a modify bit that indicates "whether its contents have changed since it was loaded into memory." Once a victim is chosen, this bit is checked.

Modify bitMeaningWhen evicting
set (1)Contents in memory differ from disk (modified)Must be written to disk
clear (0)Contents in memory are identical to diskNo need to write to disk; just discard it

Pages that were not modified can skip the write, so disk access can be cut by up to half.

Method 2: Choose a good replacement algorithm

This means choosing the victim well so that fewer page faults occur in the future. There are algorithms such as FIFO, OPT, and LRU, covered in detail with real simulation results in Page Replacement Algorithms.

Cache Memory ​

Cache memory is a small, fast storage device that temporarily keeps a copy of part of what is in main memory. It reduces the performance loss caused by the speed gap between the CPU and main memory. When the CPU looks for data it has already seen, it takes it straight from the cache instead of going all the way to memory.

TypeMain memoryCache memory
ComponentDRAMSRAM (flip-flop circuits)
SpeedSlowFast
Capacity / priceLarge and cheapSmall and expensive

How the CPU and Storage Exchange Data ​

text
CPU requests an address
   │
   ▼
Is it in the cache?
   ├── Yes (Hit)  → deliver from cache straight to the CPU → done
   └── No (Miss)  → fetch from main memory → store in cache → deliver to the CPU → done

Frequently used data must be in the cache for hits to increase and things to get faster. For that, the system must be able to predict to some degree what data the CPU will want, and this is where the principle of locality comes in.

Locality ​

Programs don't use all of memory evenly; they focus on specific parts for a while.

TypeMeaningExample
Temporal localityAn address used recently is likely to be used again soonThe variable i inside a loop
Spatial localityAddresses near the one just used are also likely to be used soonReading an array in order from the front

Cache Line ​

Even if frequently used data is in the cache, it is pointless if you have to search the whole cache to find what you want. So the cache stores data in fixed-size bundles (usually 64 bytes) and attaches a tag to each bundle indicating "which memory address this came from." Each bundle is called a cache line.

  • From the address alone, it can immediately calculate which slot to check, so it finds data quickly without searching the whole cache.
  • Even if only one byte is needed, the surrounding 64 bytes are fetched together, which takes advantage of spatial locality.

Cache structure and mapping methods are covered in more detail in Cache Memory.

Summary ​

ConceptSummary for non-CS majors
Main memoryThe work desk the CPU uses directly. A program must be loaded here to run
Logical / physical addressThe address a program sees / the actual address on RAM
MMUHardware that translates logical addresses into physical ones and prevents invading others' space
base / limitSets the boundary "only from here to here" using a start address and a size
Internal fragmentationSpace left over and wasted inside the slot you were given
External fragmentationLots of free space, but in pieces, so a large program can't fit
PagingCut into equal sizes and put in any empty slot. No external fragmentation
SegmentationSplit by meaning, such as code, data, and stack. No internal fragmentation
Virtual memoryLoad only what is needed now and pretend memory is big
SwappingTemporarily move unused contents out to disk and bring them back later
Page replacementWhen there is no free spot, evict one page and load the needed one
Modify bitSave time by discarding unchanged pages instead of writing them back to disk
Cache / localityA small, fast store that exploits the habit of reusing data often and nearby