Garbage collection and compaction
Finding memory nobody can reach any more (mark & sweep), and squeezing the holes together (compaction).
Syllabus says: “Garbage collection and compaction”
On this page · 11 sections
MARK what you can reach from the roots, SWEEP away the rest. COMPACT = push all the living blocks to one side.
Cleaning your hostel room before going home: put a sticker on everything you still use (mark), throw out everything without a sticker (sweep), then push all your stuff to one corner so there's one big free space (compaction).
Garbage collection reclaims memory that is no longer reachable from the program's roots, e.g. by marking all reachable nodes and sweeping the unmarked ones onto the free list; compaction moves allocated blocks together to form one large free block.
What you will be able to do
- Define garbage, memory leak and dangling pointer.
- Explain mark-and-sweep garbage collection.
- Explain compaction and why it needs pointer updates.
Definitions
Garbage: memory that has been allocated but is no longer reachable from any pointer in the program. Garbage collection: automatically finding and reclaiming such memory.
- Memory leak — the program forgets to free memory it no longer needs (garbage piles up).
- Dangling pointer — a pointer to memory that has already been freed; using it is a serious bug.
- Roots — global variables, local variables on the stack and CPU registers: the starting points of every pointer path.
Mark and sweep
- Mark phase: start from every root and follow pointers (DFS or BFS), setting a mark bit in every node reached.
- Sweep phase: scan the whole heap linearly. Unmarked blocks are garbage → add them to the free list. Clear the mark bit of marked blocks for the next run.
Algorithm MarkSweep()
1. for each root r do Mark(r)
2. for each block b in the heap (address order) do
3. if b.mark = false then add b to the free list // garbage
4. else b.mark ← false // reset for next time
Algorithm Mark(p)
1. if p ≠ NULL and p.mark = false then
2. p.mark ← true
3. for each pointer field q of p do Mark(q)Each block counts how many pointers refer to it; at zero it is freed immediately. It is simple and incremental, but cyclic structures (A → B → A) never reach zero, so they leak.
Compaction
Compaction moves every live block, so every pointer to a moved block must be updated (e.g. using forwarding addresses). It is expensive, so it runs only when free memory is fragmented and a request cannot be met.
Now watch it run
Every frame comes from really running the algorithm on your input — change it and break it! Tap ▶ Play, or step one frame at a time with ◀ ▶. Keys: Space play/pause, ← → step.
C implementation
memory_allocation.ctested ✓ 720/720 cases/* First-fit, best-fit and worst-fit allocation — KTU PCCST303, Module 2
* (KTU Nov 2025 Q12a, May 2026 Q12a)
* Memory is a list of segments; each segment belongs to a block and is either a hole or
* holds one process. Requests are served in order; a request that fits nowhere waits.
* split mode : the leftover part of a hole stays a (smaller) hole — variable partitions
* fixed mode : the whole hole goes to the process, leftover is wasted — fixed partitions
* Input : n size1 ... sizen scheme F|B|W mode S|X then commands until EOF:
* A size (allocate; processes are named P1, P2, ... in request order)
* F k (free process Pk: coalesce with neighbouring holes, retry waiting ones)
* C (compact: move all processes to the start, one big hole at the end)
* Output: "P<k> -> <block index>" lines (0-based), "WAIT: P..", and the final segments. */
#include <stdio.h>
#include <string.h>
#define MAXS 64
struct seg { int block, size, owner, waste; }; /* owner 0 = hole */
struct seg m[MAXS];
int nseg, nblocks, blockSize[16];
char scheme, mode;
int waitPid[32], waitSize[32], nwait;
int placedBlock[33]; /* -1 = not in memory */
/* index of the hole chosen by the current scheme, or -1 */
int chooseHole(int r) {
int i, pick = -1;
for (i = 0; i < nseg; i++) {
if (m[i].owner != 0 || m[i].size < r) continue;
if (pick == -1) pick = i;
else if (scheme == 'B' && m[i].size < m[pick].size) pick = i; /* smallest that fits */
else if (scheme == 'W' && m[i].size > m[pick].size) pick = i; /* largest */
if (scheme == 'F') break; /* first that fits */
}
return pick;
}
void place(int pid, int r, int i) {
int left = m[i].size - r;
if (mode == 'S' && left > 0) { /* split: process part + new hole */
memmove(&m[i + 2], &m[i + 1], (size_t)(nseg - i - 1) * sizeof m[0]);
nseg++;
m[i + 1].block = m[i].block; m[i + 1].size = left; m[i + 1].owner = 0; m[i + 1].waste = 0;
m[i].size = r;
} else if (mode == 'X') { m[i].size = r; m[i].waste = left; } /* rest of the block is wasted */
m[i].owner = pid;
placedBlock[pid] = m[i].block;
}
void removeSeg(int i) { memmove(&m[i], &m[i + 1], (size_t)(nseg - i - 1) * sizeof m[0]); nseg--; }
void retryWaiting(int onlyFirstFitHole) {
int k, still = 0;
for (k = 0; k < nwait; k++) {
int i;
if (onlyFirstFitHole) { for (i = 0; i < nseg && !(m[i].owner == 0 && m[i].size >= waitSize[k]); i++) { } if (i == nseg) i = -1; }
else i = chooseHole(waitSize[k]);
if (i < 0) { waitPid[still] = waitPid[k]; waitSize[still] = waitSize[k]; still++; }
else place(waitPid[k], waitSize[k], i);
}
nwait = still;
}
void freeProcess(int pid) {
int i;
for (i = 0; i < nseg && m[i].owner != pid; i++) { }
if (i == nseg) { printf("P%d is not in memory\n", pid); return; }
m[i].owner = 0; m[i].size += m[i].waste; m[i].waste = 0;
placedBlock[pid] = -1;
if (i + 1 < nseg && m[i + 1].owner == 0 && m[i + 1].block == m[i].block) { m[i].size += m[i + 1].size; removeSeg(i + 1); }
if (i > 0 && m[i - 1].owner == 0 && m[i - 1].block == m[i].block) { m[i - 1].size += m[i].size; removeSeg(i); }
retryWaiting(0);
}
void compact(void) {
int i, k = 0, total = 0, used = 0;
for (i = 0; i < nblocks; i++) total += blockSize[i];
for (i = 0; i < nseg; i++)
if (m[i].owner != 0) {
m[k] = m[i]; m[k].size += m[k].waste; m[k].waste = 0; m[k].block = 0;
used += m[k].size; placedBlock[m[k].owner] = 0; k++;
}
nseg = k;
if (total > used) { m[nseg].block = 0; m[nseg].size = total - used; m[nseg].owner = 0; m[nseg].waste = 0; nseg++; }
nblocks = 1; blockSize[0] = total;
{ /* after compaction memory is one variable region: waiting processes take what they
need from the big hole (split), first come first served */
char saved = mode;
mode = 'S';
retryWaiting(1);
mode = saved;
}
}
int main(void) {
char cmd[4], s[4], md[4];
int i, x, pid = 0;
if (scanf("%d", &nblocks) != 1 || nblocks < 1 || nblocks > 10) { printf("BAD INPUT\n"); return 1; }
for (i = 0; i < nblocks; i++) {
if (scanf("%d", &blockSize[i]) != 1) { printf("BAD INPUT\n"); return 1; }
m[i].block = i; m[i].size = blockSize[i]; m[i].owner = 0; m[i].waste = 0;
}
nseg = nblocks;
if (scanf("%3s %3s", s, md) != 2) { printf("BAD INPUT\n"); return 1; }
scheme = s[0]; mode = md[0];
for (i = 0; i < 33; i++) placedBlock[i] = -1;
while (scanf("%3s", cmd) == 1) {
if (cmd[0] == 'A' && scanf("%d", &x) == 1 && pid < 32) {
int h = chooseHole(x);
pid++;
if (h < 0) { waitPid[nwait] = pid; waitSize[nwait] = x; nwait++; }
else place(pid, x, h);
} else if (cmd[0] == 'F' && scanf("%d", &x) == 1) freeProcess(x);
else if (cmd[0] == 'C') compact();
else { printf("BAD COMMAND\n"); return 1; }
}
for (i = 1; i <= pid; i++) if (placedBlock[i] >= 0) printf("P%d -> %d\n", i, placedBlock[i]);
printf("WAIT:");
for (i = 0; i < nwait; i++) printf(" P%d", waitPid[i]);
printf("\n");
for (i = 0; i < nseg; i++) printf("SEG: %d %d %d %d\n", m[i].block, m[i].size, m[i].owner, m[i].waste);
return 0;
}
Sample run · May 2026 Q12a, best fit · real output from gcc
Input (stdin)
6 200 400 600 500 300 250 B S A 357 A 210 A 468 A 491
Output (stdout)
P1 -> 1 P2 -> 5 P3 -> 3 P4 -> 2 WAIT: SEG: 0 200 0 0 SEG: 1 357 1 0 SEG: 1 43 0 0 SEG: 2 491 4 0 SEG: 2 109 0 0 SEG: 3 468 3 0 SEG: 3 32 0 0 SEG: 4 300 0 0 SEG: 5 210 2 0 SEG: 5 40 0 0
Trade-offs
| Benefit | Cost | |
|---|---|---|
| Garbage collection | no leaks, no dangling pointers | pauses the program; extra time |
| Compaction | removes external fragmentation | must move data and update pointers |
| Manual free (C) | full control, no pauses | leaks and dangling pointers are your problem |
Quick check — can you get them all?
Practice
Every visualizer has a Practice mode: predict the next state before the animation reveals it. You can also work through the topic's question set on the practice page.
Exam-ready summary
- Garbage = allocated but unreachable memory.
- Mark & sweep: mark from roots → sweep unmarked to the free list.
- Reference counting fails on cycles.
- Compaction: move live blocks together → one big hole; update pointers.
References
- Horowitz, Sahni & Anderson-Freed, Fundamentals of Data Structures in C, 2/e — Ch. 4 (storage management)
- Jones & Lins, Garbage Collection: Algorithms for Automatic Dynamic Memory Management — Ch. 2–3
Explanations on this page are original. Textbook references point to where the standard treatment can be read; no text is reproduced from them.
Prefer revising from notes? Module-wise notes and question papers on Azhimathi Mayam (opens in a new tab)