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.