Project 6: Safe Memory Allocator Wrapper
A secure memory allocation wrapper that prevents integer overflow in size calculations, zeroes memory on free (preventing info leaks), detects double-frees, and tracks allocations for debugging.
Quick Reference
| Attribute | Value |
|---|---|
| Primary Language | C |
| Alternative Languages | C++, Rust |
| Difficulty | Level 2: Intermediate |
| Time Estimate | 1-2 weeks |
| Knowledge Area | Secure Coding / Memory Safety |
| Tooling | Valgrind, AddressSanitizer |
| Prerequisites | Project 2 (integer overflow), basic dynamic memory |
What You Will Build
A secure memory allocation wrapper that prevents integer overflow in size calculations, zeroes memory on free (preventing info leaks), detects double-frees, and tracks allocations for debugging.
Why It Matters
This project builds core skills that appear repeatedly in real-world systems and tooling.
Core Challenges
- Safe size calculation → maps to integer overflow before malloc
- Preventing use-after-free → maps to poison freed memory
- Detecting double-free → maps to allocation tracking
- Memory zeroing on free → maps to preventing info leaks
Key Concepts
- calloc vs malloc: CERT C MEM04-C
- Clearing Sensitive Data: CERT C MEM03-C
- Allocation Tracking: Valgrind internals
Real-World Outcome
$ ./test_safe_alloc
Testing safe_malloc...
✓ Normal allocation: 1024 bytes allocated
✓ Zero size: Returns NULL
✓ Overflow protection: safe_calloc(SIZE_MAX, 2) returns NULL
Testing safe_free...
✓ Memory zeroed on free (sensitive data cleared)
✓ Double-free detected: FATAL: double free at 0x12340000
✓ Use-after-free detected: Memory poisoned with 0xDEADBEEF
Testing safe_realloc...
✓ Normal realloc: 1024 -> 2048 bytes
✓ Shrink realloc: Zeroes extra bytes
✓ Overflow protection: safe_realloc(ptr, SIZE_MAX) returns NULL
Memory stats:
Allocations: 15
Frees: 14
Current allocated: 1024 bytes
LEAK DETECTED: 1 allocation not freed!
Implementation Guide
- Reproduce the simplest happy-path scenario.
- Build the smallest working version of the core feature.
- Add input validation and error handling.
- Add instrumentation/logging to confirm behavior.
- Refactor into clean modules with tests.
Milestones
- Milestone 1: Minimal working program that runs end-to-end.
- Milestone 2: Correct outputs for typical inputs.
- Milestone 3: Robust handling of edge cases.
- Milestone 4: Clean structure and documented usage.
Validation Checklist
- Output matches the real-world outcome example
- Handles invalid inputs safely
- Provides clear errors and exit codes
- Repeatable results across runs
References
- Main guide:
LEARN_SECURE_C_AND_EXPLOIT_AWARENESS.md - “Effective C, 2nd Edition” by Robert C. Seacord