Skip to content
Azhimathi Mayam logoDSA Study HubPCCST303 · KTU · S3
Module 2 · syllabusLesson live

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
ormakkurippu ✎
Never-forget card

MARK what you can reach from the roots, SWEEP away the rest. COMPACT = push all the living blocks to one side.

Picture it

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).

Write this in the exam

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

Definition

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

  1. Mark phase: start from every root and follow pointers (DFS or BFS), setting a mark bit in every node reached.
  2. 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
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)
DefinitionAnother approach: reference counting

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

A
0
1
B
2
3
4
C
5
6
D
7
Before: 4 free slots exist, but the largest hole has only 2 → a 3-slot request fails (external fragmentation).
A
0
B
1
C
2
D
3
4
5
6
7
After compaction: live blocks moved to one end; one free hole of 4.

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 ◀ ▶.

Loading visualizer…

C implementation

memory_allocation.ctested ✓ 720/720 cases
C
/* 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

Open in the Code Lab →

Trade-offs

BenefitCost
Garbage collectionno leaks, no dangling pointerspauses the program; extra time
Compactionremoves external fragmentationmust move data and update pointers
Manual free (C)full control, no pausesleaks and dangling pointers are your problem

Quick check — can you get them all?

Question 1

Q1.‘Garbage’ in memory means…

Question 2

Q2.Mark-and-sweep: the mark phase…

Question 3

Q3.Main problem solved by compaction?

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)