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 · ←→ step

What's happening

Pseudocode

    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 only in this browser — no account needed.
    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.