Next Fit Memory Allocation in OS
Like first fit, take the first hole that is big enough, but start each search where the previous one stopped instead of at the beginning, and wrap around at the end. Searches get shorter; allocations spread across all of memory.
How Next Fit Works
- Start at the hole the pointer marks (hole 1 for the first request)
- Skip holes that are too small, wrapping from the last hole to the first
- Allocate from the first hole that fits and leave the pointer there
- After one full lap with no fit, the request waits
In operating system memory management, next fit keeps one extra value, a roving pointer, that remembers where the last search ended. Each new request starts scanning from that hole instead of from the start of memory, takes the first hole big enough, and wraps back to hole 1 after the last hole. If it gets all the way round without a fit, the request waits.
Books differ on one detail: whether the pointer stays on the hole just used or moves to the hole after it. Staying is the common choice, since a split hole may still have room for the next request; this lesson uses that version, and the tracer shows how the other one changes the answer.
- One pointer of state between requests
- The lap limit stops an endless search
Worked Example: Four Requests
Free holes of 100, 500, 200, 300 and 600 KB receive 212, 417, 112 and 426 KB, with the pointer at hole 1. 212 KB: 100 is too small, 500 fits, leaving 288; the pointer stays on hole 2. 417 KB starts at hole 2: 288, 200 and 300 are too small, 600 fits, leaving 183. Four holes examined, because hole 1 was skipped.
112 KB starts at hole 5, where 183 fits at once, leaving 71. 426 KB starts at hole 5: 71, then wrap to 100, 288, 200 and 300. A full lap with no fit, so it waits with 959 KB free.
- Holes used: 2, 5, 5, then wait
- Free list after: 100, 288, 200, 300, 71 KB
- Holes examined in total: 12
Next Fit vs First Fit
The win is search length. First fit restarts at hole 1 every time and examined 14 holes on this list; the next fit algorithm examined 12, and placed the 112 KB request with a single check. On a long free list whose front is crowded with small holes, skipping that front on every request saves far more.
The loss is where the cuts land. First fit put 112 KB into the 288 KB leftover near the front, leaving 176; next fit cut it from the 183 KB hole at the far end, leaving 71 KB, a sliver. Over long runs this spreading is the measured weakness: next fit memory allocation chips at every region in turn, so large holes survive nowhere, and trace studies found it fragments memory more than first fit. Neither rule placed the 426 KB request; only best fit did.
| First fit | Next fit | |
|---|---|---|
| Where each search starts | Hole 1 | Where the last search ended |
| Holes examined | 14 | 12 |
| Leftover from the 112 KB request | 176 KB (hole 2) | 71 KB (hole 5) |
| Free list after | 100, 176, 200, 300, 183 | 100, 288, 200, 300, 71 |
- Shorter searches: the crowded front is skipped
- More scattered holes: no region is left untouched
Next fit around the ring
def next_fit(holes, size, start):
n = len(holes)
for step in range(n): # at most one full lap
i = (start + step) % n # wrap past the last hole
if holes[i] >= size:
return i, step + 1
return -1, n
holes = [100, 500, 200, 300, 600]
total = 0
pointer = 0
for size in [212, 417, 112, 426]:
i, looked = next_fit(holes, size, pointer)
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
pointer = i # the next search resumes here, not at hole 1
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}, starting the scan at `start`.
std::pair<int, int> nextFit(const std::vector<int>& holes, int size, int start) {
int n = holes.size();
for (int step = 0; step < n; ++step) { // at most one full lap
int i = (start + step) % n; // wrap past the last hole
if (holes[i] >= size) return {i, step + 1};
}
return {-1, n};
}
int main() {
std::vector<int> holes{100, 500, 200, 300, 600};
int total = 0, pointer = 0;
for (int size : {212, 417, 112, 426}) {
auto [i, looked] = nextFit(holes, size, pointer);
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
pointer = i; // the next search resumes here, not at hole 1
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}, starting the scan at start.
static int[] nextFit(int[] holes, int size, int start) {
int n = holes.length;
for (int step = 0; step < n; step++) { // at most one full lap
int i = (start + step) % n; // wrap past the last hole
if (holes[i] >= size) return new int[] {i, step + 1};
}
return new int[] {-1, n};
}
public static void main(String[] args) {
int[] holes = {100, 500, 200, 300, 600};
int total = 0, pointer = 0;
for (int size : new int[] {212, 417, 112, 426}) {
int[] r = nextFit(holes, size, pointer);
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
pointer = i; // the next search resumes here, not at hole 1
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);
}
}Step through it
Running on holes 100, 500, 200, 300, 600 KB · requests 212, 417, 112, 426 KB
Cost and Where It Fits
A single search is still O(n) in the worst case, a full lap. The saving is on average: successive searches pick up where the last left off instead of re-reading the same holes. The state is just one index, which must be fixed up when the hole it points to is merged with a neighbour or removed.
Because it spreads blocks across memory, next fit also mixes blocks from different phases of a program, which hurts locality. That is why general-purpose allocators prefer first fit or best fit with size classes, and next fit shows up mainly in exams and in simple systems where search time matters more than wasted space.
- Worst case O(n) per request; shorter on average
- Pointer must be updated when holes merge