Debug the Allocator

hard · memory, debugging, gdb

Debug the Allocator

Your colleague wrote a memory allocator, but it's crashing in production. Your task: find and fix all the bugs.

The Situation

The allocator has several bugs. Some cause immediate crashes, others cause subtle corruption. You have access to:

  1. The buggy source code
  2. Test cases that reproduce the crashes
  3. GDB for debugging

Bugs to Find

There are 4 bugs in the code:

  1. Off-by-one error - A size calculation is wrong
  2. Missing initialization - A critical field isn't set
  3. Wrong pointer arithmetic - Pointer math is incorrect
  4. Logic error - A condition is wrong

Debugging Strategy

Step 1: Compile with Debug Symbols

gcc -g -O0 solution.c test.c -o test

Step 2: Run Under GDB

gdb ./test
(gdb) run
# Wait for crash
(gdb) bt         # Backtrace - see where it crashed
(gdb) print *block  # Inspect variables

Step 3: Set Breakpoints

(gdb) break my_malloc
(gdb) break my_free
(gdb) run
(gdb) print block->magic    # Check for corruption

Step 4: Watch for Corruption

(gdb) watch block->magic
(gdb) continue
# Stops when magic changes

Your Task

Fix all 4 bugs in the provided code. The tests will tell you when you've fixed them all.

Hints

  1. Bug 1: Look at request_space - is the size calculation correct?
  2. Bug 2: Look at block_init - are all fields initialized?
  3. Bug 3: Look at payload_to_block - is the pointer arithmetic right?
  4. Bug 4: Look at find_free_block - is the condition correct?

Learning Outcome

Real allocator bugs are subtle and dangerous. This exercise teaches you:

  • How to use GDB effectively
  • Common allocator bug patterns
  • The value of magic numbers for corruption detection
Run tests to see results
No issues detected