#include #include #include "shared.h" #include "q2defines.h" // memblock struct size must be multiple of 8 bytes // for proper alignment on 64-bit systems typedef struct memblock_s { struct memblock_s *prev; struct memblock_s *next; size_t size; int tag; } memblock_t; static memblock_t *mem_head = NULL; #ifdef DEBUG static size_t numblocks = 0; static size_t numbytes = 0; #endif void *Z_TagMalloc(size_t size, int tag) { memblock_t *m; size += sizeof(memblock_t); // add room for header size = (size + 7) & ~7; // align to 64-bit bounary (needed?) m = malloc(size); if (!m) Sys_Error("Z_Malloc: failed on allocation of %u bytes\n", size); m->size = size; m->tag = tag; m->prev = NULL; m->next = mem_head; if (mem_head) mem_head->prev = m; mem_head = m; #ifdef DEBUG numblocks++; numbytes += size; #endif return (void *)((byte *)m + sizeof(memblock_t)); } void *Z_Malloc(size_t size) { return Z_TagMalloc(size, 1); } void Z_Free(void *buffer) { memblock_t *m; if (!buffer) return; m = (memblock_t *)((byte *)buffer - sizeof(memblock_t)); #ifdef DEBUG numblocks--; numbytes -= m->size; #endif if (m->prev) m->prev->next = m->next; else mem_head = m->next; if (m->next) m->next->prev = m->prev; free(m); } char *Z_Strdup(const char *in) { char *out; out = Z_Malloc(strlen(in)+1); strcpy(out, in); return out; } void Z_FreeAll() { memblock_t *m, *next; for (m = mem_head; m; m = next) { next = m->next; free(m); } mem_head = NULL; #ifdef DEBUG numblocks = 0; numbytes = 0; #endif; }