4  Memory Allocator: Interface & Data Structures

This section covers the zone memory allocator’s interface in z_zone.h: purge-tag macros, API prototypes, memblock_t layout, and Z_ChangeTag macro.

Next we’ll look at DOOM’s memory management system in z_zone.h, which defines memory block tags and allocation functions.


4.0.1 πŸ“„ File: z_zone.h (lines 36–44)

Memory blocks are tagged with PU_* values to control their lifetime. Tags below 100 persist for specific durations; tags 100 and above (PU_PURGELEVEL, PU_CACHE) are reclaimable.


4.0.2 πŸ“„ File: z_zone.h (lines 47–55)

Memory allocator functions: - Z_Init: Initialize heap - Z_Malloc: Allocate memory - Z_Free: Free memory - Z_FreeTags: Free blocks by tag - Z_DumpHeap, Z_FileDumpHeap: Debug heap - Z_CheckHeap: Validate heap - Z_ChangeTag2: Modify tag - Z_FreeMemory: Query memory


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

memblock_t forms a doubly linked list. Each block has: - size - user pointer (or NULL if free) - tag for purge priority - id for validity - next and prev links


The next steps demonstrate two key memblock_t operations: converting between user pointers and block headers in Z_Free, and traversing the block chain in Z_FreeTags.


4.0.4 πŸ“„ File: z_zone.c (lines 127–130)

In Z_Free, the block header is retrieved by subtracting sizeof(memblock_t) from the user pointer. The id field is checked for validity.


4.0.5 πŸ“„ File: z_zone.c (lines 304–307)

Z_FreeTags traverses the doubly linked block list using the next pointer from blocklist.


4.0.6 πŸ“„ File: z_zone.h (lines 72–77)

The Z_ChangeTag macro validates the pointer and forwards to Z_ChangeTag2 to change the memory block’s tag.


4.0.7 πŸ“„ File: r_data.c (lines 286–288)

Once a texture column is cached, Z_ChangeTag re-tags it as PU_CACHE, allowing it to be purged later.


4.0.8 πŸ“„ File: s_sound.c (lines 543–547)

If a sound effect’s usefulness underflows, Z_ChangeTag re-tags its data block as PU_CACHE to make it reclaimable.


4.0.9 πŸ“„ File: g_game.c (lines 1661–1663)

After quitting a demo, Z_ChangeTag re-tags demobuffer as PU_CACHE, enabling memory recovery.


That completes the tour of z_zone.h’s interface and core data structures for Doom’s memory allocator.