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.