Debug the Allocator
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:
- The buggy source code
- Test cases that reproduce the crashes
- GDB for debugging
Bugs to Find
There are 4 bugs in the code:
- Off-by-one error - A size calculation is wrong
- Missing initialization - A critical field isn't set
- Wrong pointer arithmetic - Pointer math is incorrect
- 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
- Bug 1: Look at
request_space- is the size calculation correct? - Bug 2: Look at
block_init- are all fields initialized? - Bug 3: Look at
payload_to_block- is the pointer arithmetic right? - 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