Lion Cipher Lab
Write your own memory allocator (malloc/free) from scratch
- Foundations
- Advanced
- ~90 min
- Free · no account required
Why it matters
Every C and C++ program you will ever analyze, and the runtime under most other languages, gets its dynamic memory from one function: malloc, paired with free. To a beginner malloc is a black box that 'gives you memory.' But the exploitation world lives INSIDE that black box: the entire family of heap attacks -- the House of Force, House of Botcake, House of Einherjar, House of Orange, House of Spirit, tcache poisoning, use-after-free -- works by corrupting the allocator's own bookkeeping (chunk headers, free-list pointers, the top chunk) so that a later malloc hands the attacker a pointer to…
What you'll learn
- how a process actually gets heap memory from the kernel: sbrk/brk grow the program break, mmap serves large allocations directly
- designing a chunk header (size + in-use bit) so free() can recover all its bookkeeping from just the caller's pointer
- maintaining an address-ordered free list and doing first-fit allocation (and how best-fit trades speed for less waste)
- implementing free() that marks a chunk free and COALESCES adjacent free chunks to fight fragmentation
- splitting an oversized free chunk so the leftover stays usable instead of being wasted
- enforcing 8/16-byte alignment on every returned pointer and understanding why malloc is required to
- naming the failure modes real allocators must solve: internal vs external fragmentation, a single global free list that doesn't scale, zero thread-safety
- connecting the mental model to exploitation: this chunk metadata is exactly what House-of-* and tcache-poisoning attacks corrupt
Steps in this lab
- The one idea: the kernel gives you a blank region; malloc is the librarian that hands out pieces
- Get a Linux x86-64 shell and a C compiler
- The design: a chunk header, an address-ordered free list, and five small jobs
- Write the allocator: myalloc.c
- Run it -- watch chunks coalesce, split, and route to mmap with your own eyes
- The named failure modes (why this allocator is a teaching tool, not a shippable one)
- How real allocators differ -- and why THIS metadata is what heap exploits corrupt
- The judgment: when to write your own allocator, and when to never