Lesson 18 · Memory management

External Fragmentation in OS

Enough memory is free in total, but it is split into holes between live blocks and none of them is big enough. A request for one contiguous block fails with memory to spare.

External Fragmentation in OS concept diagramA visual explanation of the layout and operations shown in this lesson.A 12Kfree 12KE 5Kfree 24KH 20Kfree 3K39 KB free in total — and a 26 KB request that cannot be servedthe request: 26 KB, contiguouslargest single hole: 24 KB2 KB short — and the other 15 KB is elsewherecompaction slides the blocks together and merges the holes into one 39 KB runbut only if addresses are translated at runtime — otherwise moving a block breaks its pointers
1

What External Fragmentation Is

In operating system memory management, external fragmentation is free memory that lies between allocated blocks in pieces too small to satisfy a request. The total free memory is enough; no single piece is. It affects any scheme that gives each process one contiguous block of variable size: variable partitions, segmentation, and heap allocators such as malloc.

It builds up as processes of different sizes come and go. Each exit leaves a hole where the process was. Holes that touch are merged into one (coalescing), but holes with a live block between them cannot be, so free memory ends up spread across the region in short runs.

  • Where: between allocated blocks
  • Cause: variable-sized blocks allocated and freed over time
  • Symptom: a request fails while total free memory exceeds it
2

Worked Example: 39 KB Free, 26 KB Fails

A 76 KB region holds A (12 KB), B (12 KB), E (5 KB), C (24 KB) and H (20 KB), with 3 KB free at the end. B exits, then C. The holes are now 12, 24 and 3 KB: 39 KB free, more than half the region.

A process asks for 26 KB. The 12 KB hole is too small, the 24 KB hole is 2 KB short and the 3 KB hole is far too small, so the request fails. E sits between the two larger holes; if E exits, its 5 KB joins both and one 41 KB hole forms, and 26 KB fits.

The same thing ends the textbook exercise in first fit: after 212, 417 and 112 KB are placed, holes of 100, 176, 200, 300 and 183 KB hold 959 KB, and a 426 KB request still waits.

  • Free: 39 KB · largest hole: 24 KB · request: 26 KB
  • One more exit next to the holes would merge them
3

How to Measure It

A simple measure is 1 − largest hole / total free memory. It is 0 when all free memory is one run and approaches 1 when free memory is many small pieces. In the example it is 1 − 24/39 = 38%; in the textbook first-fit run it is 1 − 300/959 = 69%. A request fails when it is larger than the largest hole, so the largest hole, not the total, is the number that decides.

Linux reports the same idea per memory zone in /proc/buddyinfo, which counts free blocks of each power-of-two size. Plenty of free pages but no free blocks of the larger orders means physical memory is fragmented.

  • Track total free and largest hole separately
  • 38% in the example, 69% in the textbook run
Implementation

External fragmentation, hole by hole

REGION = [("A", 12), ("B", 12), ("E", 5), ("C", 24), ("H", 20), (None, 3)]
PAGE = 4


def holes(region):
    out, run = [], 0
    for name, size in region:
        if name is None:
            run += size
        elif run:
            out.append(run)
            run = 0
    if run:
        out.append(run)
    return out


def free(region, name):
    return [(None if n == name else n, s) for n, s in region]


def report(region, request):
    h = holes(region)
    total, largest = sum(h), max(h)
    print("holes:", " ".join(str(x) for x in h), "KB")
    print(f"total free {total} KB, largest hole {largest} KB")
    verdict = "fits" if largest >= request else "fails"
    print(f"request {request} KB -> {verdict}")
    print(f"external fragmentation: 1 - {largest}/{total} = {(1 - largest / total) * 100:.0f}%")


region = free(free(REGION, "B"), "C")
report(region, 26)
pages = (26 + PAGE - 1) // PAGE
frames = sum(x // PAGE for x in holes(region))
print(f"with {PAGE} KB pages: {pages} pages needed, {frames} whole frames free -> fits")
print("after E exits:")
report(free(region, "E"), 26)
#include <cstdio>
#include <string>
#include <utility>
#include <vector>
using namespace std;

using Region = vector<pair<string, int>>;  // name "" means free

vector<int> holes(const Region& region) {
    vector<int> out;
    int run = 0;
    for (auto& [name, size] : region) {
        if (name.empty()) run += size;
        else if (run) { out.push_back(run); run = 0; }
    }
    if (run) out.push_back(run);
    return out;
}

Region freeBlock(Region region, const string& name) {
    for (auto& b : region) if (b.first == name) b.first = "";
    return region;
}

void report(const Region& region, int request) {
    vector<int> h = holes(region);
    int total = 0, largest = 0;
    printf("holes:");
    for (int x : h) { printf(" %d", x); total += x; if (x > largest) largest = x; }
    printf(" KB\n");
    printf("total free %d KB, largest hole %d KB\n", total, largest);
    printf("request %d KB -> %s\n", request, largest >= request ? "fits" : "fails");
    printf("external fragmentation: 1 - %d/%d = %.0f%%\n", largest, total, (1.0 - (double)largest / total) * 100);
}

int main() {
    Region start = {{"A", 12}, {"B", 12}, {"E", 5}, {"C", 24}, {"H", 20}, {"", 3}};
    const int page = 4;
    Region region = freeBlock(freeBlock(start, "B"), "C");
    report(region, 26);
    int pages = (26 + page - 1) / page, frames = 0;
    for (int x : holes(region)) frames += x / page;
    printf("with %d KB pages: %d pages needed, %d whole frames free -> fits\n", page, pages, frames);
    printf("after E exits:\n");
    report(freeBlock(region, "E"), 26);
}
import java.util.ArrayList;
import java.util.List;

public class Main {
    record Block(String name, int size) {}  // name null means free

    static List<Integer> holes(List<Block> region) {
        List<Integer> out = new ArrayList<>();
        int run = 0;
        for (Block b : region) {
            if (b.name() == null) run += b.size();
            else if (run > 0) { out.add(run); run = 0; }
        }
        if (run > 0) out.add(run);
        return out;
    }

    static List<Block> free(List<Block> region, String name) {
        List<Block> out = new ArrayList<>();
        for (Block b : region) out.add(name.equals(b.name()) ? new Block(null, b.size()) : b);
        return out;
    }

    static void report(List<Block> region, int request) {
        List<Integer> h = holes(region);
        int total = 0, largest = 0;
        StringBuilder sb = new StringBuilder("holes:");
        for (int x : h) { sb.append(" ").append(x); total += x; largest = Math.max(largest, x); }
        System.out.println(sb + " KB");
        System.out.println("total free " + total + " KB, largest hole " + largest + " KB");
        System.out.println("request " + request + " KB -> " + (largest >= request ? "fits" : "fails"));
        System.out.printf("external fragmentation: 1 - %d/%d = %.0f%%%n", largest, total, (1.0 - (double) largest / total) * 100);
    }

    public static void main(String[] args) {
        List<Block> start = List.of(new Block("A", 12), new Block("B", 12), new Block("E", 5),
            new Block("C", 24), new Block("H", 20), new Block(null, 3));
        int page = 4;
        List<Block> region = free(free(start, "B"), "C");
        report(region, 26);
        int pages = (26 + page - 1) / page, frames = 0;
        for (int x : holes(region)) frames += x / page;
        System.out.println("with " + page + " KB pages: " + pages + " pages needed, " + frames + " whole frames free -> fits");
        System.out.println("after E exits:");
        report(free(region, "E"), 26);
    }
}
Watch it run

Step through it

Running on 76 KB region: A 12, B 12, E 5, C 24, H 20 KB, 3 KB free · B and C exit · request 26 KB

76 KB region, contiguous allocationA 120B 1212E 524C 2429H 205337376free 3 KB · largest hole 3 KBeach process needs one contiguous blockaddresses in KB under the strip3 KB free in one run
Step 1

A full region, one small hole

Five blocks fill a 76 KB region, with a 3 KB hole at the end. One hole is not fragmentation: free memory is in a single run, so any request up to 3 KB can be placed and anything larger simply does not fit in what is free. Fragmentation needs free memory in more than one piece.

Output
1 / 9
4

The Fifty-Percent Rule

Knuth's fifty percent rule describes first fit after a long run of allocations and frees: in the steady state there are about half as many holes as allocated blocks. With N blocks there are about N/2 holes, and if holes are about as large as blocks, roughly a third of memory sits in holes.

The rule is why no placement rule cures the problem. Memory allocation algorithms only decide which hole a request cuts; first fit and best fit waste the least in simulations, and every rule still leaves holes behind.

  • N blocks, about N/2 holes
  • Up to a third of memory in holes
5

How It Is Fixed

Compaction moves the live blocks together so the holes merge into one run. It needs addresses that are translated at run time, since moving a block must not break the addresses the process holds, and it costs a copy of every moved byte. Memory fragmentation and compaction covers when it is possible and how much it moves.

Paging removes the cause instead. A process is cut into fixed-size pages and any page may go in any free frame, so a request never needs one contiguous run: the 26 KB request becomes 7 pages in frames that do not touch. The cost is internal fragmentation in the last page, at most one page per allocation. Segmentation keeps variable-sized segments, so it still suffers external fragmentation unless the segments are themselves paged.

  • Compaction: merge holes by moving blocks
  • Paging: no contiguous run needed
  • Segmentation alone still fragments