Lesson 20 · Memory management

First Fit Memory Allocation in OS

Scan the free holes from the start of memory and use the first one that is big enough. The search stops there, so it is short, and the unused part of the hole stays free for later requests.

First Fit Memory Allocation in OS concept diagramA visual explanation of the layout and operations shown in this lesson.a 212 KB request — first fit stops at the first hole that fits100 KBtoo small500 KBfits — take it200 KBnever examined300 KBnever examined600 KBnever examinedscan starts heretakes 500 KB · leaves 288 KBa remainder still big enough to serve a later requestabout half the list is walked on average — the shortest search of the four
1

How First Fit Works

  1. Start at the first hole in the free list
  2. If the hole is smaller than the request, move to the next one
  3. If it is big enough, allocate from it and stop searching
  4. Keep the unused part as a new hole in the same place
  5. If the list runs out, the request waits

In operating system memory management, first fit places a process in the first free hole, counting from the lowest address, that is large enough to hold it. No later hole is compared, so the search ends as soon as one fits. With variable partitions the hole is then split: the process takes its share and the rest stays free as a smaller hole.

  • One comparison per hole until the first fit
  • No sorting and no extra state between requests
2

Worked Example: Four Requests

Free holes of 100, 500, 200, 300 and 600 KB receive 212, 417, 112 and 426 KB, the same list used in every lesson of this group. For 212 KB, hole 1 (100) is too small and hole 2 (500) fits: allocate, leaving 288. Two holes examined.

For 417 KB the scan passes 100, 288, 200 and 300 before hole 5 (600) fits, leaving 183: five holes examined. For 112 KB, hole 2's 288 fits on the second look, leaving 176. For 426 KB no hole is big enough: the largest is 300, so the request waits with 959 KB free.

  • Holes used: 2, 5, 2, then wait
  • Free list after: 100, 176, 200, 300, 183 KB
  • Holes examined in total: 14
3

Where It Wins and Where It Loses

The win is speed. The best fit and worst fit rules look at all five holes for every request, 20 in total, while the first fit algorithm stopped after 2 holes twice. On a long free list the gap grows: a full scan always reads every hole, an early stop often reads only a few.

The loss on this list is the 426 KB request. Taking the 500 KB hole for 212 KB, simply because it came first, left nothing below the 600 KB hole big enough for 417 KB, so the 600 was cut too. Best fit took the tighter 300 KB hole for 212 and still had the 600 whole at the end. First fit does better than best fit on leftovers, though: its smallest leftover is 176 KB, while best fit's are 83, 88 and 88.

  • Faster: 14 holes examined against 20
  • Leftovers stay usable: 176 and 183 KB, not slivers
  • Can spend a large hole that a later large request needed
Implementation

First fit, request by request

def first_fit(holes, size):
    for i, hole in enumerate(holes):
        if hole >= size:
            return i, i + 1  # stop: later holes are never examined
    return -1, len(holes)


holes = [100, 500, 200, 300, 600]
total = 0
for size in [212, 417, 112, 426]:
    i, looked = first_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> firstFit(const std::vector<int>& holes, int size) {
    for (int i = 0; i < (int)holes.size(); ++i)
        if (holes[i] >= size) return {i, i + 1};  // stop: later holes are never examined
    return {-1, (int)holes.size()};
}

int main() {
    std::vector<int> holes{100, 500, 200, 300, 600};
    int total = 0;
    for (int size : {212, 417, 112, 426}) {
        auto [i, looked] = firstFit(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[] firstFit(int[] holes, int size) {
        for (int i = 0; i < holes.length; i++)
            if (holes[i] >= size) return new int[] {i, i + 1}; // stop: later holes are never examined
        return new int[] {-1, holes.length};
    }

    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 = firstFit(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

first fit: the first hole ≥ the requestrequest 212 KBhole 1100 KBhole 2500 KBhole 3200 KBhole 4300 KBhole 5600 KBread 0 · total 0scan order: hole 1, 2, 3, 4, 5requests to come: 212, 417, 112, 426 KBrule: stop at the first hole that is big enough
Step 1

Start at hole 1

Five free holes, lowest address first, and the first request asks for 212 KB. First fit always begins at hole 1 and walks right. It does not look at sizes in advance or sort anything; it only asks of each hole in turn: are you big enough?

Output
1 / 10
4

Cost and the Crowded Front

The worst case is O(n) per request for n holes, when the only fitting hole is the last one or none fits. Because every search starts at the beginning, small leftovers pile up near the low addresses and each request must step over them first: in the example, the 100 KB hole 1 was examined by all four requests and never used.

That crowding is what next fit tries to avoid by resuming where the last search ended. Even so, simulations rank first fit memory allocation close to best fit on wasted space and ahead of it on speed, which is why it is the usual default and why the address-ordered version appears in real allocators.

  • Worst case O(n) per request; often much less
  • Unused small holes at the front are re-checked on every request