Lesson 19 · Memory management

Memory Allocation Algorithms

When a process needs one unbroken block of memory and several free holes are big enough, the allocator must pick one. Four placement rules make that choice differently, and on the same request list they place different holes, waste different amounts and fail on different requests.

Memory Allocation Algorithms concept diagramA visual explanation of the layout and operations shown in this lesson.one 212 KB request, one hole list, three different answers100 KB500 KBfirst fit200 KB300 KBbest fit600 KBworst fitfirst fittakes 500 (first that fits)leaves 288 KBfastest — stops scanning earlybest fittakes 300 (tightest)leaves 88 KBa sliver nothing can useworst fittakes 600 (largest)leaves 388 KBburns the hole big requests need
1

The Placement Problem

Contiguous memory allocation gives each process one unbroken run of physical memory. As processes start and finish, free memory turns into a list of holes of different sizes scattered between the blocks in use. When a request arrives and more than one hole is big enough, something has to decide which hole to use. The rules that make that decision are the memory allocation algorithms that OS courses teach, and the general question is called the dynamic storage allocation problem.

The choice matters because of what it leaves behind. Taking 212 KB from a 300 KB hole leaves 88 KB; taking it from a 600 KB hole leaves 388 KB but uses up the biggest hole on the list. Whatever is left must serve every request that comes later, so a placement that looks fine now can make a later request wait.

  • Input: a list of free holes and one request size
  • Output: the hole to use, or 'wait' when none is big enough
  • The leftover becomes a smaller hole for later requests
2

Fixed and Variable Partitions

Textbooks pose the same exercise under two partition allocation methods, which is why answer keys for it sometimes disagree. With fixed partitions, memory is divided in advance and each partition holds at most one process; the unused rest of a partition is wasted (internal fragmentation). With variable partitions, the chosen hole is split: the process takes what it needs and the remainder goes back on the free list as a new, smaller hole.

When a block is freed, a variable-partition allocator merges it with any free neighbours (coalescing), so two adjacent holes become one bigger hole. The worked example on this page uses variable partitions, the setting in the Silberschatz exercise.

The two settings on the same request list
Fixed partitionsVariable partitions
Partition sizesSet in advanceCreated by each request
Processes per partitionOneOne per block; the rest stays free
Unused spaceLocked inside the partitionReturned as a smaller hole
112 KB under the first-hole ruleGoes to the 200 KB partitionGoes to the 288 KB leftover
  • Fixed: simple, but space inside a partition is lost
  • Variable: holes split and merge, so the free list keeps changing
3

The Four Placement Rules

  1. First fit: scan from the start of the list and take the first hole that is big enough
  2. Next fit: the same, but resume the scan where the previous search ended
  3. Best fit: scan every hole and take the smallest one that is big enough
  4. Worst fit: scan every hole and take the largest

Each rule answers 'which hole?' with a different preference. Two stop scanning early; two must look at every hole before they can choose.

  • Early stop: the first two rules; full scan: the last two
  • Each fit lesson traces its own rule on the example below
Implementation

Four placement rules on one hole list

def first_fit(holes, size, start):
    for i, hole in enumerate(holes):
        if hole >= size:
            return i, i + 1  # stop at the first hole that fits
    return -1, len(holes)


def best_fit(holes, size, start):
    best = -1
    for i, hole in enumerate(holes):
        if hole >= size and (best < 0 or hole < holes[best]):
            best = i  # tightest fit so far
    return best, len(holes)


def worst_fit(holes, size, start):
    worst = -1
    for i, hole in enumerate(holes):
        if hole >= size and (worst < 0 or hole > holes[worst]):
            worst = i  # largest fit so far
    return worst, len(holes)


def next_fit(holes, size, start):
    n = len(holes)
    for step in range(n):
        i = (start + step) % n  # resume where the last search ended
        if holes[i] >= size:
            return i, step + 1
    return -1, n


def run(name, rule):
    holes = [100, 500, 200, 300, 600]
    picks, total, pointer = [], 0, 0
    for size in [212, 417, 112, 426]:
        i, looked = rule(holes, size, pointer)
        total += looked
        if i < 0:
            picks.append("-")  # no hole is big enough: the request waits
        else:
            holes[i] -= size  # split: the rest stays free
            pointer = i
            picks.append(str(i + 1))
    print(f"{name:<9} holes {' '.join(picks)}  examined {total}  free {' '.join(map(str, holes))}")


run("first fit", first_fit)
run("next fit", next_fit)
run("best fit", best_fit)
run("worst fit", worst_fit)
#include <iomanip>
#include <iostream>
#include <string>
#include <utility>
#include <vector>

using Holes = std::vector<int>;
using Rule = std::pair<int, int> (*)(const Holes&, int, int);

std::pair<int, int> firstFit(const Holes& h, int size, int) {
    for (int i = 0; i < (int)h.size(); ++i)
        if (h[i] >= size) return {i, i + 1};  // stop at the first hole that fits
    return {-1, (int)h.size()};
}

std::pair<int, int> bestFit(const Holes& h, int size, int) {
    int best = -1;
    for (int i = 0; i < (int)h.size(); ++i)
        if (h[i] >= size && (best < 0 || h[i] < h[best])) best = i;  // tightest fit so far
    return {best, (int)h.size()};
}

std::pair<int, int> worstFit(const Holes& h, int size, int) {
    int worst = -1;
    for (int i = 0; i < (int)h.size(); ++i)
        if (h[i] >= size && (worst < 0 || h[i] > h[worst])) worst = i;  // largest fit so far
    return {worst, (int)h.size()};
}

std::pair<int, int> nextFit(const Holes& h, int size, int start) {
    int n = h.size();
    for (int step = 0; step < n; ++step) {
        int i = (start + step) % n;  // resume where the last search ended
        if (h[i] >= size) return {i, step + 1};
    }
    return {-1, n};
}

void run(const std::string& name, Rule rule) {
    Holes holes{100, 500, 200, 300, 600};
    std::string picks;
    int total = 0, pointer = 0;
    for (int size : {212, 417, 112, 426}) {
        auto [i, looked] = rule(holes, size, pointer);
        total += looked;
        if (!picks.empty()) picks += " ";
        if (i < 0) {
            picks += "-";  // no hole is big enough: the request waits
        } else {
            holes[i] -= size;  // split: the rest stays free
            pointer = i;
            picks += std::to_string(i + 1);
        }
    }
    std::cout << std::left << std::setw(9) << name << " holes " << picks << "  examined " << total << "  free";
    for (int h : holes) std::cout << " " << h;
    std::cout << "\n";
}

int main() {
    run("first fit", firstFit);
    run("next fit", nextFit);
    run("best fit", bestFit);
    run("worst fit", worstFit);
}
public class Main {

    interface Rule {
        int[] pick(int[] holes, int size, int start); // {hole index or -1, holes examined}
    }

    static int[] firstFit(int[] h, int size, int start) {
        for (int i = 0; i < h.length; i++)
            if (h[i] >= size) return new int[] {i, i + 1}; // stop at the first hole that fits
        return new int[] {-1, h.length};
    }

    static int[] bestFit(int[] h, int size, int start) {
        int best = -1;
        for (int i = 0; i < h.length; i++)
            if (h[i] >= size && (best < 0 || h[i] < h[best])) best = i; // tightest fit so far
        return new int[] {best, h.length};
    }

    static int[] worstFit(int[] h, int size, int start) {
        int worst = -1;
        for (int i = 0; i < h.length; i++)
            if (h[i] >= size && (worst < 0 || h[i] > h[worst])) worst = i; // largest fit so far
        return new int[] {worst, h.length};
    }

    static int[] nextFit(int[] h, int size, int start) {
        int n = h.length;
        for (int step = 0; step < n; step++) {
            int i = (start + step) % n; // resume where the last search ended
            if (h[i] >= size) return new int[] {i, step + 1};
        }
        return new int[] {-1, n};
    }

    static void run(String name, Rule rule) {
        int[] holes = {100, 500, 200, 300, 600};
        StringBuilder picks = new StringBuilder();
        int total = 0, pointer = 0;
        for (int size : new int[] {212, 417, 112, 426}) {
            int[] r = rule.pick(holes, size, pointer);
            total += r[1];
            if (picks.length() > 0) picks.append(" ");
            if (r[0] < 0) {
                picks.append("-"); // no hole is big enough: the request waits
            } else {
                holes[r[0]] -= size; // split: the rest stays free
                pointer = r[0];
                picks.append(r[0] + 1);
            }
        }
        StringBuilder free = new StringBuilder();
        for (int h : holes) free.append(" ").append(h);
        System.out.println(String.format("%-9s", name) + " holes " + picks + "  examined " + total + "  free" + free);
    }

    public static void main(String[] args) {
        run("first fit", Main::firstFit);
        run("next fit", Main::nextFit);
        run("best fit", Main::bestFit);
        run("worst fit", Main::worstFit);
    }
}
Watch it run

Step through it

Running on holes 100, 500, 200, 300, 600 KB · requests 212, 417, 112, 426 KB

holes 1 to 5, before any requestfirst fit100 KB500 KB200 KB300 KB600 KBnext fit100 KB500 KB200 KB300 KB600 KBbest fit100 KB500 KB200 KB300 KB600 KBworst fit100 KB500 KB200 KB300 KB600 KB1,700 KB free · requests 212, 417, 112, 426 KB = 1,167 KBevery row starts from the same listsame input for all four rules
Step 1

Five holes, four requests

Free memory is five holes of 100, 500, 200, 300 and 600 KB, 1,700 KB in all, and four requests arrive in order: 212, 417, 112 and 426 KB, 1,167 KB together. There is enough memory overall; the question is whether it stays in holes big enough for each request, and that depends on which hole each rule cuts.

Output
1 / 9
4

One Example, Four Answers

Free holes of 100, 500, 200, 300 and 600 KB (1,700 KB in total) receive requests of 212, 417, 112 and 426 KB, in that order. The table shows which hole each rule uses (hole 1 is the 100 KB one) and how many holes it examined in all.

Only the tightest-hole rule places the 426 KB request, because it never touched the 600 KB hole until then. The other three end with 959 KB free but no single hole larger than 300 KB, so 426 KB must wait even though there is more than twice that much free memory. The trade is visible in the leftovers: the tightest-hole rule ends with holes of 83, 88 and 88 KB, slivers too small for most later requests.

Holes 100, 500, 200, 300, 600 KB; variable partitions
Rule212417112426Holes examinedFree list after
First fit252waits14100, 176, 200, 300, 183
Next fit255waits12100, 288, 200, 300, 71
Best fit423520100, 83, 88, 88, 174
Worst fit525waits20100, 83, 200, 300, 276
  • Fewest holes examined: next fit (12), then first fit (14)
  • All four placed: best fit only, at the cost of three slivers
  • Worst fit spent the 600 KB hole on the very first request
5

Which Rule Works Best

One short list proves little, so the standard answer comes from simulation. Silberschatz summarises it: first fit and best fit both beat worst fit on speed and on how much memory stays usable; neither of the two is clearly better on memory, and first fit is usually faster because it stops early. Later studies of real program traces (Wilson and colleagues, 1995) found best fit and address-ordered first fit both waste very little, while next fit tends to fragment memory more than first fit because it spreads blocks across the whole heap.

Even the good rules lose memory between blocks. Knuth's fifty-percent rule says that, in a steady state under first fit, there are about half as many holes as allocated blocks; if holes and blocks were similar in size, about a third of memory would sit in holes. Ways to recover that space are covered in memory fragmentation and compaction, and paging avoids the problem by giving up on contiguous blocks.

  • Worst fit finishes last in simulations on both speed and memory
  • First fit is the usual default: simple, fast and close to best fit on memory
  • Next fit scans less but leaves more scattered holes over long runs
6

Making the Search Fast

On a plain unsorted list every rule costs O(n) per request in the worst case, where n is the number of holes, and the full-scan rules always pay the whole n. Real allocators change the data structure instead of the rule. Keeping holes in a balanced tree ordered by size finds the tightest fit in O(log n); a max-heap gives the largest hole in O(1) and updates in O(log n); keeping the list in address order makes merging freed neighbours cheap.

General-purpose allocators go further and keep separate free lists per size class, so most requests are served from the right list without scanning. Doug Lea's dlmalloc, the basis of glibc's malloc, works roughly like best fit inside those size bins. Operating system kernels such as Linux use a buddy allocator for physical pages, which only ever splits blocks in halves so merging is a quick check.

  • Unsorted list: O(n) per request
  • Size-ordered tree: tightest hole in O(log n)
  • Size-class lists and buddy systems replace the scan in practice