From e153be0be2fb8df6656292daab3fa59963c76737 Mon Sep 17 00:00:00 2001 From: 3gg <3gg@shellblade.net> Date: Tue, 13 Feb 2024 17:51:51 -0800 Subject: Let memory allocators trap by default when attempting to allocate beyond capacity. --- mem/src/mem.c | 12 ++++++++++++ 1 file changed, 12 insertions(+) (limited to 'mem/src') diff --git a/mem/src/mem.c b/mem/src/mem.c index 056d947..2904035 100644 --- a/mem/src/mem.c +++ b/mem/src/mem.c @@ -1,5 +1,7 @@ #include "mem.h" +#include + #include #include @@ -13,6 +15,7 @@ bool mem_make_( mem->block_size_bytes = block_size_bytes; mem->num_blocks = num_blocks; mem->next_free_chunk = 0; + mem->trap = true; // Allocate chunks and blocks if necessary and zero them out. if (!chunks) { @@ -107,6 +110,10 @@ void* mem_alloc_(Memory* mem, size_t num_blocks) { mem->next_free_chunk = mem->chunks[chunk_idx].next; return &mem->blocks[chunk_idx * mem->block_size_bytes]; } else { + if (mem->trap) { + FAIL("Memory allocation failed, increase the allocator's capacity or " + "avoid fragmentation."); + } return 0; // Large-enough free chunk not found. } } @@ -186,3 +193,8 @@ size_t mem_capacity_(const Memory* mem) { assert(mem); return mem->num_blocks * mem->block_size_bytes; } + +void mem_enable_traps_(Memory* mem, bool enable) { + assert(mem); + mem->trap = enable; +} -- cgit v1.2.3