G27
Self-checkedTier 1 14 min reados.memory-management-basics

Memory management: partitioning and fragmentation

Sharing main memory among processes by contiguous allocation: fixed and variable partitions, the first, best, worst and next fit placement rules, internal and external fragmentation, compaction, swapping, and the buddy system.

Why it exists

Main memory is limited and many processes want it at once. The operating system has to decide where in memory each process goes, keep processes from touching each other's memory, and make good use of what exists. The oldest and simplest scheme gives each process one contiguous block of memory. It is easy to understand and is the setting for classic GATE questions on placement rules and fragmentation. Its weaknesses, wasted space and the need to find a big enough hole, are the reasons paging was invented (paging).

Prerequisites

No other concept page is needed. It helps to know that main memory is one level of the memory hierarchy, larger and slower than the cache, smaller and faster than the disk.

Precise definitions

Aims of memory management. Relocation (a program may be loaded anywhere), protection (a process cannot touch another's memory or the operating system's), sharing (controlled shared memory, shared code), logical organisation (modules, segments), and efficient use of physical memory.

Contiguous allocation. Each process occupies a single contiguous block. Memory is divided between the operating system (usually the low or the high end) and user processes.

  • Fixed (static) partitioning: memory is divided in advance into partitions, of equal or different sizes. A process is loaded into a free partition that is large enough. The degree of multiprogramming is limited by the number of partitions.
  • Variable (dynamic) partitioning: partitions are created as needed. A process gets exactly the memory it requests. When a process ends, its block becomes a hole; adjacent holes are merged (coalesced).

Fragmentation. Memory that is free but cannot be used.

  • Internal fragmentation: wasted memory inside an allocated block, because the block is larger than the request. Typical of fixed partitions (a 130 KB process in a 200 KB partition wastes 70 KB), of the buddy system, and of paging (the last page of a process).
  • External fragmentation: enough free memory in total, but split into holes that are each too small for the request. Typical of variable partitions and of segmentation.

Placement algorithms (for variable partitions). When a request of size nn arrives, choose a hole of size at least nn:

AlgorithmRule
First fitthe first hole (lowest address) that is big enough; stop searching
Next fitlike first fit, but the search starts where the previous search ended, wrapping round
Best fitthe smallest hole that is big enough (the smallest leftover)
Worst fitthe largest hole (the largest leftover, hoping it is still useful)

In all of them the process takes the part of the hole at its low end and the rest remains a smaller hole. Best fit must search the whole list (unless it is sorted by size) and tends to leave many tiny, useless holes. First fit is usually fast and about as good as best fit in practice. Worst fit tends to break up the large holes that big requests need, and does worst in simulations. No rule is best for every request sequence: one may succeed where another fails, in either direction.

Compaction. Move the processes to one end of memory so that all the holes join into one large hole. It cures external fragmentation, but costs time (every moved process is copied) and works only if the processes can be relocated at run time (the addresses are bound at execution time; see process address space).

Swapping. A process can be moved temporarily out of memory to a backing store (a fast disk) and brought back later to continue. It lets the total memory demand exceed physical memory and makes room for higher-priority processes. The cost is dominated by the transfer: swap time =process sizetransfer rate= \dfrac{\text{process size}}{\text{transfer rate}}, once out and once in.

Buddy system. Memory of size 2k2^k is split in halves repeatedly. A request is rounded up to a power of two and served from a block of exactly that size, splitting a larger free block if necessary. When a block is freed it is merged with its buddy (the other half of the block it was split from) if the buddy is free too. Fast to find the buddy (the buddy of a block of size ss at address aa is at a⊕sa \oplus s, the bitwise exclusive or), but it suffers internal fragmentation. Example: a request of 70 KB in a 1024 KB memory is rounded up to 128 KB, wasting 58 KB.

How it works

The animations apply each placement rule to the same memory and the same four requests. Memory is 2000 KB. Processes A to E are loaded and between them are five holes of 100, 450, 300, 550 and 250 KB. Four processes arrive in order, P1 (210 KB), P2 (480 KB), P3 (150 KB) and P4 (400 KB), and each needs one contiguous block. Watch which hole each rule picks and what is left.

First fit places P1 in the 450 KB hole, P2 in the 550 KB hole, P3 in the 240 KB remainder. P4 needs 400 KB; the holes are 100, 90, 300, 70 and 250: no single hole is large enough, although the total free memory is 810 KB. That is external fragmentation.

Contiguous allocation: first fit: start

Allocation simulated, not typed

first fit (the first hole that is big enough). Memory of 2000 KB.

free
A
free
450
B
free
300
C
free
550
D
free
250
E
request
-
total free
1650
largest hole
550
holes
100, 450, 300, 550, 250

Step 0

Memory of 2000 KB. Five processes (A to E) are in memory and between them lie five holes of 100, 450, 300, 550, 250 KB. Four new processes arrive in turn and each needs ONE contiguous block. The rule for choosing a hole is first fit (the first hole that is big enough).

0 / 5
computed by script: the algorithm or the translation is executed, one event per step. python3 scripts/gen-os-mem-traces.py

Best fit places P1 in the smallest hole that fits (250), P2 in 550, P3 in 300 and P4 in 450. Every request is satisfied.

Contiguous allocation: best fit: start

Allocation simulated, not typed

best fit (the smallest hole that is big enough). Memory of 2000 KB.

free
A
free
450
B
free
300
C
free
550
D
free
250
E
request
-
total free
1650
largest hole
550
holes
100, 450, 300, 550, 250

Step 0

Memory of 2000 KB. Five processes (A to E) are in memory and between them lie five holes of 100, 450, 300, 550, 250 KB. Four new processes arrive in turn and each needs ONE contiguous block. The rule for choosing a hole is best fit (the smallest hole that is big enough).

0 / 5
computed by script: the algorithm or the translation is executed, one event per step. python3 scripts/gen-os-mem-traces.py

Worst fit puts P1 in the largest hole (550), which leaves only 450 and 340 for P2 (needs 480): it fails; later P4 fails too.

Contiguous allocation: worst fit: start

Allocation simulated, not typed

worst fit (the largest hole). Memory of 2000 KB.

free
A
free
450
B
free
300
C
free
550
D
free
250
E
request
-
total free
1650
largest hole
550
holes
100, 450, 300, 550, 250

Step 0

Memory of 2000 KB. Five processes (A to E) are in memory and between them lie five holes of 100, 450, 300, 550, 250 KB. Four new processes arrive in turn and each needs ONE contiguous block. The rule for choosing a hole is worst fit (the largest hole).

0 / 5
computed by script: the algorithm or the translation is executed, one event per step. python3 scripts/gen-os-mem-traces.py

Next fit continues the search from the last placement, so P3 is placed after P2 (in the last hole) and P4 fails like in first fit.

Contiguous allocation: next fit: start

Allocation simulated, not typed

next fit (continue from the last placement). Memory of 2000 KB.

free
A
free
450
B
free
300
C
free
550
D
free
250
E
request
-
total free
1650
largest hole
550
holes
100, 450, 300, 550, 250

Step 0

Memory of 2000 KB. Five processes (A to E) are in memory and between them lie five holes of 100, 450, 300, 550, 250 KB. Four new processes arrive in turn and each needs ONE contiguous block. The rule for choosing a hole is next fit (continue from the last placement).

0 / 5
computed by script: the algorithm or the translation is executed, one event per step. python3 scripts/gen-os-mem-traces.py

Compaction. First fit again, but when P4 fails the processes are slid together. All 810 KB of free memory become one hole and P4 fits.

First fit, then compaction when a request fails: start

Allocation simulated, not typed

first fit (the first hole that is big enough), with compaction. Memory of 2000 KB.

free
A
free
450
B
free
300
C
free
550
D
free
250
E
request
-
total free
1650
largest hole
550
holes
100, 450, 300, 550, 250

Step 0

Memory of 2000 KB. Five processes (A to E) are in memory and between them lie five holes of 100, 450, 300, 550, 250 KB. Four new processes arrive in turn and each needs ONE contiguous block. The rule for choosing a hole is first fit (the first hole that is big enough), with compaction.

0 / 7
computed by script: the algorithm or the translation is executed, one event per step. python3 scripts/gen-os-mem-traces.py

Worked examples

EX 1The four rules, by program

Easy

A C program places the same four requests under each rule and reports the leftover.

#include <stdio.h>
 
#define NB 10                               /* blocks in memory: processes and holes in address order */
#define NR 4
 
struct block { const char *owner; int size; };           /* owner NULL means a hole */
 
static void run(const char *name, int algo) {
    struct block b[32] = {{0, 100}, {"A", 60}, {0, 450}, {"B", 80}, {0, 300}, {"C", 70}, {0, 550}, {"D", 90}, {0, 250}, {"E", 50}};
    int n = NB, last = 0;
    const char *rname[NR] = {"P1", "P2", "P3", "P4"};
    int rsize[NR] = {210, 480, 150, 400};
    printf("%-9s", name);
    for (int r = 0; r < NR; r++) {
        int pick = -1;
        for (int k = 0; k < n; k++) {
            int i = algo == 3 ? (last + k) % n : k;             /* next fit starts where the last placement was made */
            if (b[i].owner || b[i].size < rsize[r]) continue;
            if (algo == 0 || algo == 3) { pick = i; break; }
            if (pick < 0 || (algo == 1 && b[i].size < b[pick].size) || (algo == 2 && b[i].size > b[pick].size)) pick = i;
        }
        if (pick < 0) { printf("  %s: no hole", rname[r]); continue; }
        int start = 0;
        for (int i = 0; i < pick; i++) start += b[i].size;
        printf("  %s: at %d", rname[r], start);
        int rest = b[pick].size - rsize[r];
        b[pick].owner = rname[r]; b[pick].size = rsize[r];
        if (rest) {
            for (int i = n; i > pick + 1; i--) b[i] = b[i - 1];
            b[pick + 1].owner = 0; b[pick + 1].size = rest; n++;
        }
        last = pick;
    }
    int freeb = 0, largest = 0;
    for (int i = 0; i < n; i++) if (!b[i].owner) { freeb += b[i].size; if (b[i].size > largest) largest = b[i].size; }
    printf("   | free %d, largest hole %d\n", freeb, largest);
}
 
int main(void) {
    run("first", 0);
    run("best", 1);
    run("worst", 2);
    run("next", 3);
    return 0;
}
first      P1: at 160  P2: at 1060  P3: at 370  P4: no hole   | free 810, largest hole 300
best       P1: at 1700  P2: at 1060  P3: at 690  P4: at 160   | free 410, largest hole 150
worst      P1: at 1060  P2: no hole  P3: at 160  P4: no hole   | free 1290, largest hole 340
next       P1: at 160  P2: at 1060  P3: at 1700  P4: no hole   | free 810, largest hole 300

Reading it. Best fit is the only rule that places all four requests here; first and next fit fail P4; worst fit fails P2 and P4. After first fit, the 810 KB that is free is split into holes of at most 300 KB, so a 400 KB request fails: external fragmentation. After worst fit, 1290 KB is free but no hole reaches 480. The result depends on the sequence: with a different list of requests a different rule would win, which is why no placement rule is "best" in general.

EX 2Internal or external?

Easy

Memory is divided into fixed partitions of 200 KB. A process of 130 KB occupies one: 70 KB is wasted inside the partition (internal fragmentation). Another process of 210 KB cannot fit in any partition, although three partitions of 200 KB are free: it simply cannot run. Now take variable partitions with holes of 100 KB, 60 KB and 90 KB, a total of 250 KB free: a 150 KB request cannot be satisfied: external fragmentation (enough in total, not contiguous). Rule: waste inside an allocated block is internal; free space split into unusable pieces outside the blocks is external.

EX 3Compaction: when it works and what it costs

Medium

In the last animation, 810 KB of free memory is split into holes of 100, 90, 300, 70 and 250 KB. Compaction moves processes A, P1, P3, B, C, P2, D and E (1190 KB in all) towards address 0, so that one hole of 810 KB remains at the top; P4 (400 KB) is then placed, leaving a hole of 410 KB. The price: up to 1190 KB of data is copied (at 1 GB per second that is about 1 ms, during which the processes cannot run), and every moved process needs its base register updated, so the run-time relocation hardware must exist. With absolute or load-time addresses the processes cannot be moved at all.

EX 4Swapping time

Medium

A process of 100 MB is swapped out to a disk that transfers 50 MB per second. Swap-out takes 100/50=2100/50 = 2 s; bringing a process of the same size back takes 2 s, so replacing one with another of equal size costs about 4 s plus seek and latency time. That is why a time quantum of a few milliseconds is far too short for swapping: the cost would dominate. A system must therefore swap only processes that are idle, and only the memory actually used need be swapped.

EX 5The buddy system

GATE level

A buddy allocator manages 1024 KB. A request of 70 KB is rounded up to 128 KB: the 1024 block is split into two 512 KB buddies, one of them into two 256 KB buddies, one of them into two 128 KB buddies, and one 128 KB block is given to the process; 58 KB is wasted (internal fragmentation). A request of 129 KB needs a 256 KB block. When a block of size ss at address aa is freed, its buddy is at a⊕sa \oplus s; if the buddy is also free, they merge into a block of size 2s2s at a  &  ¬sa \;\&\; \lnot s. For example, the buddy of the 128 KB block at address 256 is at 256⊕128=384256 \oplus 128 = 384, and merging gives the 256 KB block at 256. (The exclusive-or rule was checked for every block size up to 512 and every aligned address below 1024.)

Cheat box

Cheat box

  • Contiguous allocation: one block per process. Fixed partitions: internal fragmentation. Variable partitions: external fragmentation.
  • First fit: first big-enough hole. Next fit: continue from the last. Best fit: smallest big-enough. Worst fit: largest.
  • No rule always wins; best fit leaves tiny holes, worst fit destroys big ones. The process takes the low end of the hole.
  • External fragmentation: total free ≥\ge request, but no single hole is big enough. Cure: compaction (needs run-time relocation) or non-contiguous allocation (paging).
  • Internal fragmentation: waste inside the allocated block (fixed partitions, buddy, last page).
  • Swap time == size / transfer rate, once out and once in.
  • Buddy: round up to a power of two; buddy of (a,s)(a, s) is a⊕sa \oplus s.

Traps and GATE patterns

Connections

Paging removes external fragmentation by letting a process occupy non-contiguous frames (paging); segmentation allows several contiguous pieces of varying sizes per process but brings back external fragmentation (segmentation). Compaction and swapping rely on addresses being bound at run time (process address space). Swapping a process in and out is a decision of the medium-term scheduler (CPU scheduling).

PYQs

3 previous year questions from your book. I re-solved each one myself (2 by running or simulating, 1 by reasoning only); the book's key is shown next to my answer. All PYQs

GATE 2026 · NATQ1 · page 340 of the book
Consider contiguous allocation of physical memory
to processes using a variable partitioning scheme.
Suppose there are 8 holes in the memory of sizes:

20 KB, 4 KB, 25 KB, 18 KB, 7 KB, 9 KB, 15 KB,
and 12 KB.

Assume that no two holes are adjacent.

Two processes arrive in order:
●
P1 = 16 KB
●
P2 = 9 KB

They are allocated memory using the best-fit
technique.

After allocating space to P1 and P2, the number of
holes of size less than 8 KB is ______.

Note: 1K = 210.
GATE 2020 · MCQ · 1 markQ18 · page 343 of the book
Consider allocation of memory to a new process.
Assume that none of the existing holes in the
memory will exactly fit the process's memory
requirement. Hence, a new hole of smaller size will
be created if allocation is made in any of the
existing holes. Which one of the following
statements is TRUE?
  • (a)The hole created by the worst fit is always larger than the hole created by the first fit.
  • (b)The hole created by best fit is never larger than the hole created by first fit.
  • (c)The hole created by the first fit is always larger than the hole created by the next fit.
  • (d)The hole created by the next fit is never larger than the hole created by the best fit.
GATE 2015 · MCQQ27 · page 344 of the book
Consider six memory partitions of size 200 KB,
400 KB, 600 KB, 500 KB, 300 KB, and 250 KB,
where KB refers to kilobyte. These partitions need
to be allotted to four processes of sizes 357 KB, 210
KB, 468 KB and 491 KB in that order. If the best
fit algorithm is used, which partitions are NOT
allotted to any process?
  • (a)200 KB and 300 KB
  • (b)200 KB and 250 KB
  • (c)250 KB and 300 KB
  • (d)300 KB and 400 KB

Self-check

Question 1

Holes of 120, 80, 200 and 150 KB (in this order). A request of 90 KB arrives. Which hole do first fit, best fit and worst fit choose?

Show answer

First fit: 120 (the first that is big enough). Best fit: 120 is the smallest hole that fits (80 is too small). Worst fit: 200.

Question 2

After the 90 KB request is placed by best fit, a request of 110 KB arrives. Which hole does best fit take?

Show answer

The holes are now 30, 80, 200, 150. The smallest that fits 110 is 150.

Question 3

A buddy system serves a request of 200 KB. What block does it use and how much is wasted?

Show answer

A 256 KB block; 256−200=56256 - 200 = 56 KB is wasted.

Question 4

Why can compaction not be used when programs use absolute addresses?

Show answer

Moving a process changes the physical addresses it occupies, but absolute addresses in the code would still point to the old place. Only run-time relocation (a base register) lets the process be moved.

Revision card

One-screen revision

  • Fixed partitions: internal fragmentation. Variable partitions: external fragmentation, holes, coalescing.
  • First fit, next fit, best fit, worst fit; process at the low end of the hole; ties to the lowest address.
  • External fragmentation: total free enough, no single hole. Compaction needs run-time binding.
  • Swap time == size / rate. Buddy: power-of-two blocks, buddy =a⊕s= a \oplus s, internal fragmentation.

References

  • ·Silberschatz, Galvin, Gagne, Operating System Concepts, Chapter 9 Main Memory (swapping, contiguous memory allocation, fragmentation)
  • ·Tanenbaum and Bos, Modern Operating Systems, Chapter 3 Memory Management (swapping, managing free memory)
  • ·Stallings, Operating Systems: Internals and Design Principles, Chapter 7 Memory Management (partitioning, the buddy system)

Verification

Every placement shown (first, best, worst and next fit on the page's memory, and the compaction run) is produced by an allocator in scripts/gen-os-mem-traces.py. scripts/enum-checks/os_mem.py compares it with a second, independently written allocator (holes kept as start-and-size pairs) on 3000 random layouts and request sequences for all four rules, and checks conservation of memory, coalescing of freed neighbours and compaction. The C program on this page (npm run verify:c) is a third implementation and prints the same placements; tests/os-mem-traces.test.ts re-derives each placement. The buddy rule (the buddy of a block of size s at address a is at a XOR s) is checked for every block size up to 512 and every aligned address below 1024. The fixed-partition and swapping numbers are plain arithmetic. Conventions that change answers: a process is placed at the LOW end of the hole it takes; ties go to the lowest address; next fit continues from the hole used last. Textbook chapter titles are from memory. SECOND PASS (2026-11-02, done by the assistant, not a human check): every Self-check question was solved before the printed answer was read and all agreed; the definitions, worked examples, cheat box and traps were read claim by claim and the numbers re-derived by hand. No defect found. Status raised to self-checked; verified needs a textbook or human check.

last verified: never