Project 24: Memory Leak Detector
Project 24: Memory Leak Detector
Interpose
malloc/freeat runtime, track allocations, and emit a leak report with stack traces.
Quick Reference
| Attribute | Value |
|---|---|
| Difficulty | Advanced |
| Time Estimate | 1-2 weeks |
| Language | C (Alternatives: C++) |
| Prerequisites | Comfortable with dynamic linking concepts, basic stack traces |
| Key Topics | Interposition, dlsym, allocation tracking, “no malloc in malloc” |
| CS:APP Chapters | 7 (linking), 9 (malloc), 3 (debugging) |
1. Learning Objectives
By completing this project, you will:
- Use library interposition (
LD_PRELOADon Linux;DYLD_INSERT_LIBRARIESon macOS) to intercept allocation APIs - Avoid recursion pitfalls in allocators (bootstrapping your own metadata)
- Record useful diagnostics (sizes, call stacks, aggregate by callsite)
2. Project Specification
Build a shared library libleakcheck.so (or .dylib) that:
- Wraps
malloc/calloc/realloc/free - Tracks live allocations and total bytes
- On process exit, prints a sorted leak report
3. Design Notes
- Metadata storage options:
- Fixed-size static table (fast, simple, bounded)
mmap-backed arena to avoid callingmallocinternally
- Stack traces:
- Use
backtrace()if available, or capture return addresses manually (frame pointers help)
- Use
4. Testing Strategy
- Create small intentionally-leaky programs with known leaks and sizes.
- Validate “no false positives” for correctly-freed paths.
- Stress test: many small allocations; ensure performance remains reasonable.
5. Extensions
- Detect double-free and invalid-free with clear diagnostics.
- Add “allocation lifetime” stats and high-water marks.
- Emit JSON suitable for CI parsing.
6. Reference Reading
- CS:APP 3e — Ch. 7 (Interposition), Ch. 9 (Dynamic memory)