1. Home
  2. Operating Systems
  3. Memory Allocation (First, Next, Best & Worst Fit)

Memory Allocation (First, Next, Best & Worst Fit)

Free memory is split into holes of different sizes. Which hole should each new process get? Four strategies, four different results.

Interactive 3DBeginner10 min readOSUpdated

Drag to rotate · Right-drag to pan · Click, then scroll to zoom · Space play · Left arrowRight arrow step

What's happening

Memory has free holes of different sizes, and processes arrive needing space. Which hole should each process get? Four classic strategies give different results. Pick one and press Run.

Pseudocode

  1. for each process P (in order):
  2. scan the holes from the start of memory
  3. put P in the first hole with size ≥ P
  4. the rest of that hole stays free
  5. no hole big enough → P must wait
Read this model as text · 28 steps

One run of the model above, written out step by step. Useful with a screen reader, on a slow connection, or for quick revision. The values may differ from the run on your screen.

  1. Memory has free holes of different sizes, and processes arrive needing space. Which hole should each process get? Four classic strategies give different results. Pick one and press Run.
  2. First fit: take the first hole that is big enough. Memory has holes of 100K, 500K, 200K, 300K, 600K. Processes arrive in order: P1 (212K), P2 (417K), P3 (112K), P4 (426K).
  3. P1 needs 212K.
  4. Check the hole of 100K: 212 > 100 — too small, keep looking.
  5. Check the hole of 500K: 212 ≤ 500 — it fits! Stop searching.
  6. Put P1 into the 500K hole. 288K of it stays free.
  7. P1 is in memory. The leftover hole is 288K.
  8. P2 needs 417K.
  9. Check the hole of 100K: 417 > 100 — too small, keep looking.
  10. Check the hole of 288K: 417 > 288 — too small, keep looking.
  11. Check the hole of 200K: 417 > 200 — too small, keep looking.
  12. Check the hole of 300K: 417 > 300 — too small, keep looking.
  13. Check the hole of 600K: 417 ≤ 600 — it fits! Stop searching.
  14. Put P2 into the 600K hole. 183K of it stays free.
  15. P2 is in memory. The leftover hole is 183K.
  16. P3 needs 112K.
  17. Check the hole of 100K: 112 > 100 — too small, keep looking.
  18. Check the hole of 288K: 112 ≤ 288 — it fits! Stop searching.
  19. Put P3 into the 288K hole. 176K of it stays free.
  20. P3 is in memory. The leftover hole is 176K.
  21. P4 needs 426K.
  22. Check the hole of 100K: 426 > 100 — too small, keep looking.
  23. Check the hole of 176K: 426 > 176 — too small, keep looking.
  24. Check the hole of 200K: 426 > 200 — too small, keep looking.
  25. Check the hole of 300K: 426 > 300 — too small, keep looking.
  26. Check the hole of 183K: 426 > 183 — too small, keep looking.
  27. No single hole is big enough for P4 (426K), so it must wait — even though 959K is free in total! The free memory is split into pieces: external fragmentation.
  28. First fit placed 3 of 4 processes; P4 must wait. Free memory left: 959K, largest hole 300K. Try another strategy, or press Compare all.

Try this in the 3D model

  • Run First fit on the textbook example. Why does P4 (426K) have to wait?
  • Run Best fit. Every process fits. Which choice made the difference?
  • Run Worst fit. What happens to the big 600K hole?
  • Press Compare all, then Random a few times. Is one strategy always the winner?

The problem

When processes start and finish, the free memory gets chopped into holes of different sizes scattered around RAM. A new process needs one contiguous block. If several holes are big enough, which one should it get?

Think of parking cars of different lengths along a street with gaps of different sizes. Squeeze a small car into the smallest gap that fits, and the long gaps stay free for buses. Park it in the first gap you see, and you may block the only spot a bus could use.

The four strategies

Strategy Rule Idea
First fit The first hole big enough Fast: stop searching as soon as possible
Next fit Like first fit, but start where the last search stopped Spreads allocations around memory
Best fit The smallest hole big enough Keep big holes for big processes
Worst fit The largest hole Leave big leftovers that are still useful

Whatever hole is chosen, the process takes what it needs from the start of the hole, and the rest stays free as a smaller hole.

The textbook example

Holes: 100K, 500K, 200K, 300K, 600K (in memory order). Processes: P1 = 212K, P2 = 417K, P3 = 112K, P4 = 426K.

Process First fit Best fit Worst fit
P1 (212K) 500K → 288K left 300K → 88K left 600K → 388K left
P2 (417K) 600K → 183K left 500K → 83K left 500K → 83K left
P3 (112K) 288K → 176K left 200K → 88K left 388K → 276K left
P4 (426K) must wait 600K → 174K left must wait

Only best fit places all four processes in this example. With first fit, 959K is still free when P4 arrives, more than twice what it needs, but the largest hole is only 300K.

Fragmentation

  • External fragmentation: the free memory is enough in total, but it is split into pieces that are each too small. That is what blocks P4 above. A famous rule of thumb, the 50-percent rule, says first fit can lose about one third of memory this way.
  • Internal fragmentation: memory is handed out in fixed-size units, so a process gets slightly more than it asked for and the extra is wasted inside its block.

Two cures for external fragmentation:

  1. Compaction: move the processes together so the holes merge into one. It works, but copying memory is slow.
  2. Paging: split every process into small fixed-size pages that can go into any free frame, so memory no longer has to be contiguous. This is what modern operating systems do. See paging and page replacement.

Which strategy is best?

Simulations show first fit and best fit both beat worst fit at using memory, and first fit is usually faster because it stops early. Best fit tends to leave many tiny, useless holes. Worst fit destroys the big holes that big processes need. There is no strategy that wins on every input. Try Random in the 3D model and see.

Code

def allocate(holes, procs, strategy):
    holes = holes[:]                          # free hole sizes, in memory order
    result, last = [], 0
    for p in procs:
        fits = [i for i, h in enumerate(holes) if h >= p]
        if not fits:
            result.append(None)               # must wait
            continue
        if strategy == "first":
            i = fits[0]
        elif strategy == "next":
            i = next((j for j in fits if j >= last), fits[0])
        elif strategy == "best":
            i = min(fits, key=lambda j: holes[j])
        else:                                 # worst
            i = max(fits, key=lambda j: holes[j])
        result.append(holes[i])
        holes[i] -= p                         # the rest of the hole stays free
        last = i
    return result

holes, procs = [100, 500, 200, 300, 600], [212, 417, 112, 426]
for s in ("first", "best", "worst"):
    print(s, allocate(holes, procs, s))
# first [500, 600, 288, None]
# best [300, 500, 200, 600]
# worst [600, 500, 388, None]

Common mistakes

  • Thinking the whole hole is used up. Only the process’s size is taken, and the leftover stays free.
  • Forgetting that holes keep their memory order for first fit and next fit.
  • Mixing up best and worst fit: best fit takes the smallest hole that fits, worst fit the largest.
  • Calling P4’s problem “not enough memory”. The total is enough; it is external fragmentation.

Complexity at a glance

Case / operationTimeWhy
First fitO(h)Stops at the first hole that fits (h = number of holes).
Next fitO(h)Like first fit, but starts where the last search ended.
Best fit / Worst fitO(h)Must look at every hole (O(log h) with a sorted tree of holes).
Extra spaceO(h) to keep the list of holes

Quick check

Test yourself — pick an answer to see if you got it.

1. Holes are 100K, 500K, 200K, 300K, 600K. Where does best fit put a 212K process?

2. What is external fragmentation?

3. Which strategy leaves the largest leftover holes?

4. How can the operating system get rid of external fragmentation?

Saved in this browser.
Spotted a mistake or a bug in the 3D model?

Report a mistake

in Memory Allocation (First, Next, Best & Worst Fit). Thank you — every report makes the lesson better for the next reader.

We'll also include a link to the step of the 3D model you're on and your browser type, so we can reproduce it.