5  Memory Allocator: Implementation & Algorithms

This tour examines z_zone.c, Doom’s zone memory allocator. The tour covers the heap container definition, zone initialization, memory allocation and deallocation operations, block splitting and merging, and heap management utilities for debugging and maintenance.


5.0.1 πŸ“„ File: z_zone.c (lines 46–60)

memzone_t tracks memory allocation with a size counter, block list, and search pointer. mainzone is the global instance.


5.0.2 πŸ“„ File: z_zone.h (lines 58–66)

Z_ClearZone resets a zone to contain a single free block, with rover pointing to its start.


5.0.3 πŸ“„ File: z_zone.c (lines 67–86)

Z_Init obtains heap memory from I_ZoneBase and sets up a single free block spanning the entire space.


5.0.4 πŸ“„ File: z_zone.c (lines 93–116)

Tags control how long blocks stay allocated.


Next we’ll look at Z_Malloc, which handles memory allocation requests in Doom’s zone allocator.


5.0.5 πŸ“„ File: z_zone.h (line 36)

PU_STATIC marks a block as static for the program’s duration β€” never purged.


5.0.6 πŸ“„ File: z_zone.h (line 43)

Z_Malloc searches from mainzone->rover for a free block, purging blocks with tag β‰₯ PU_PURGELEVEL or skipping others.


When a block has enough extra space (>64 bytes), Z_Malloc splits it into an allocated block and a new free block.


5.0.7 πŸ“„ File: z_zone.c (lines 195–203)

Z_Malloc marks the found block as in use, optionally sets a back-pointer, and moves rover for the next allocation.


5.0.8 πŸ“„ File: z_zone.c (lines 205–244)

Z_Free returns memory by marking a block as free and merging with neighbors. Validates ZONEID, clears ownership, and ensures proper linkage.


5.0.9 πŸ“„ File: z_zone.c (lines 247–265)

Frees all memory blocks whose tags fall within the given range.


5.0.10 πŸ“„ File: z_zone.c (lines 267–286)

Prepares to inspect the heap and perform maintenance/debugging operations.


5.0.11 πŸ“„ File: z_zone.c (lines 122–172)

Z_DumpHeap prints diagnostic info for memory blocks within a tag range.


5.0.12 πŸ“„ File: z_zone.c (lines 296–317)

Traverses the block list to print details and verify integrity invariants.


Z_FileDumpHeap writes the heap’s block list and integrity results to a file.


5.0.13 πŸ“„ File: z_zone.c (lines 326–334)

Z_CheckHeap checks block list structure and usage correctness.


5.0.14 πŸ“„ File: z_zone.c (lines 339–359)

Changes a block’s tag after confirming memory safety and purge eligibility.


5.0.15 πŸ“„ File: z_zone.c (lines 366–392)

Z_FreeMemory sums all unused and purgeable memory blocks to estimate allocatable bytes.


5.0.16 πŸ“„ File: z_zone.c (lines 399–419)

And that’s it! You’ve explored Doom’s memory management system from structures to strategies and the tools that keep it stable.