Lesson 22 · Memory management

Worst Fit Memory Allocation in OS

Always allocate from the largest free hole, so the piece left over is big enough to be useful. It avoids tiny leftovers, but it spends the large holes first, and a large request later may find none.

Worst Fit Memory Allocation in OS concept diagramA visual explanation of the layout and operations shown in this lesson.worst fit spends the largest hole first — including on small requestsbefore: a 212 KB request600 KB — the largest300 KB200 KBtakes 600, leaves 388 — a fine remainderlater: a 420 KB request388 KB300 KB200 KBno hole fits — 888 KB free, request failsthe big holes are gone, so the big request starves on plenty of free memory
1

How Worst Fit Works

  1. Scan every hole and remember the largest
  2. If the largest is smaller than the request, the request waits
  3. Otherwise allocate from it and keep the remainder free

In operating system memory management, worst fit gives a process the largest free hole on the list. The idea is the opposite of best fit: instead of leaving the smallest possible remainder, leave the biggest, so the leftover can still hold a later process rather than becoming a useless sliver.

  • Only the largest hole matters, so one check decides failure
  • No early exit on a plain list
2

Worked Example: Four Requests

Free holes of 100, 500, 200, 300 and 600 KB receive 212, 417, 112 and 426 KB. 212 KB goes to hole 5 (600), the largest, leaving 388. 417 KB now finds 500 as the largest and takes hole 2, leaving 83.

112 KB goes to hole 5 again, since 388 is now the largest, leaving 276. 426 KB finds the largest hole is only 300 KB and waits, with 959 KB free across five holes.

  • Holes used: 5, 2, 5, then wait
  • Free list after: 100, 83, 200, 300, 276 KB
  • Holes examined in total: 20
3

Where It Wins and Where It Loses

The win is medium-sized leftovers. After the first request the worst fit algorithm left 388 KB where best fit left 88. By the end it holds three holes of at least 200 KB (200, 300 and 276), against two for first fit and none for best fit, so a run of 200 KB requests would go further under worst fit.

The loss is the large request. The 600 KB hole was the only one that could ever hold 426 KB, and worst fit spent it on a 212 KB request at the very start. The pattern repeats on any list: every request, however small, cuts the biggest hole, so the sizes level out. Five 100 KB requests on the starting list leave worst fit with holes of 100, 300, 200, 300 and 300 KB, while first fit, serving the same five, still has its 600 KB hole whole.

  • Leaves the most medium holes for medium requests
  • Destroys the large holes that large requests need
  • Levels hole sizes downward over time
Implementation

Worst fit, request by request

def worst_fit(holes, size):
    worst = -1
    for i, hole in enumerate(holes):
        if hole >= size and (worst < 0 or hole > holes[worst]):
            worst = i  # larger than any fit seen so far
    return worst, len(holes)  # every hole is examined


holes = [100, 500, 200, 300, 600]
total = 0
for size in [212, 417, 112, 426]:
    i, looked = worst_fit(holes, size)
    total += looked
    if i < 0:
        print(f"{size} KB -> waits, largest hole is {max(holes)} KB, examined {looked}")
    else:
        holes[i] -= size  # the rest of the hole stays free
        print(f"{size} KB -> hole {i + 1}, leaves {holes[i]} KB, examined {looked}")
print("free list:", *holes)
print("holes examined:", total)
#include <algorithm>
#include <iostream>
#include <utility>
#include <vector>

// Returns {hole index or -1, holes examined}.
std::pair<int, int> worstFit(const std::vector<int>& holes, int size) {
    int worst = -1;
    for (int i = 0; i < (int)holes.size(); ++i)
        if (holes[i] >= size && (worst < 0 || holes[i] > holes[worst]))
            worst = i;  // larger than any fit seen so far
    return {worst, (int)holes.size()};  // every hole is examined
}

int main() {
    std::vector<int> holes{100, 500, 200, 300, 600};
    int total = 0;
    for (int size : {212, 417, 112, 426}) {
        auto [i, looked] = worstFit(holes, size);
        total += looked;
        if (i < 0) {
            std::cout << size << " KB -> waits, largest hole is "
                      << *std::max_element(holes.begin(), holes.end())
                      << " KB, examined " << looked << "\n";
        } else {
            holes[i] -= size;  // the rest of the hole stays free
            std::cout << size << " KB -> hole " << i + 1 << ", leaves " << holes[i]
                      << " KB, examined " << looked << "\n";
        }
    }
    std::cout << "free list:";
    for (int h : holes) std::cout << " " << h;
    std::cout << "\nholes examined: " << total << "\n";
}
public class Main {

    // Returns {hole index or -1, holes examined}.
    static int[] worstFit(int[] holes, int size) {
        int worst = -1;
        for (int i = 0; i < holes.length; i++)
            if (holes[i] >= size && (worst < 0 || holes[i] > holes[worst]))
                worst = i; // larger than any fit seen so far
        return new int[] {worst, holes.length}; // every hole is examined
    }

    public static void main(String[] args) {
        int[] holes = {100, 500, 200, 300, 600};
        int total = 0;
        for (int size : new int[] {212, 417, 112, 426}) {
            int[] r = worstFit(holes, size);
            int i = r[0], looked = r[1];
            total += looked;
            if (i < 0) {
                int largest = 0;
                for (int h : holes) largest = Math.max(largest, h);
                System.out.println(size + " KB -> waits, largest hole is " + largest + " KB, examined " + looked);
            } else {
                holes[i] -= size; // the rest of the hole stays free
                System.out.println(size + " KB -> hole " + (i + 1) + ", leaves " + holes[i] + " KB, examined " + looked);
            }
        }
        StringBuilder sb = new StringBuilder("free list:");
        for (int h : holes) sb.append(" ").append(h);
        System.out.println(sb);
        System.out.println("holes examined: " + total);
    }
}
Watch it run

Step through it

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

worst fit: always the largest holerequest 212 KB100 KBhole 1500 KBhole 2200 KBhole 3300 KBhole 4600 KBhole 5requests: 212, 417, 112, 426 KB, in orderrule: maximise the leftover
Step 1

Bars by size: the tallest is next

Each bar is a free hole, its height its size. Worst fit ignores where a hole is and always takes the tallest bar that fits, so finding it means reading every hole. The reasoning: a big hole minus the request still leaves a big, useful piece.

Output
1 / 8
4

Cost and Measured Results

On a plain list, worst fit memory allocation reads every hole per request, O(n). A max-heap keyed on hole size gives the largest hole in O(1) and restores order after a split in O(log n), which makes it the cheapest of the four rules to speed up.

Speed does not rescue it. In the classic simulations reported by Silberschatz, worst fit came last on both time and storage use, behind first fit and best fit. It is taught mainly to show that a sensible-sounding rule, keeping leftovers big, fails once the whole request sequence is considered.

  • Plain list O(n); max-heap O(log n) per request
  • Last in simulations on speed and storage