diff options
author | 3gg <3gg@shellblade.net> | 2024-02-13 17:51:51 -0800 |
---|---|---|
committer | 3gg <3gg@shellblade.net> | 2024-02-13 17:51:51 -0800 |
commit | e153be0be2fb8df6656292daab3fa59963c76737 (patch) | |
tree | 7cca3fc134553017cb3c259db1dca33c98556109 /mem/src/mem.c | |
parent | 84bdfa4a23f5b8daa7921541b007518bc634be0f (diff) |
Let memory allocators trap by default when attempting to allocate beyond capacity.
Diffstat (limited to 'mem/src/mem.c')
-rw-r--r-- | mem/src/mem.c | 12 |
1 files changed, 12 insertions, 0 deletions
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 @@ | |||
1 | #include "mem.h" | 1 | #include "mem.h" |
2 | 2 | ||
3 | #include <cassert.h> | ||
4 | |||
3 | #include <stdlib.h> | 5 | #include <stdlib.h> |
4 | #include <string.h> | 6 | #include <string.h> |
5 | 7 | ||
@@ -13,6 +15,7 @@ bool mem_make_( | |||
13 | mem->block_size_bytes = block_size_bytes; | 15 | mem->block_size_bytes = block_size_bytes; |
14 | mem->num_blocks = num_blocks; | 16 | mem->num_blocks = num_blocks; |
15 | mem->next_free_chunk = 0; | 17 | mem->next_free_chunk = 0; |
18 | mem->trap = true; | ||
16 | 19 | ||
17 | // Allocate chunks and blocks if necessary and zero them out. | 20 | // Allocate chunks and blocks if necessary and zero them out. |
18 | if (!chunks) { | 21 | if (!chunks) { |
@@ -107,6 +110,10 @@ void* mem_alloc_(Memory* mem, size_t num_blocks) { | |||
107 | mem->next_free_chunk = mem->chunks[chunk_idx].next; | 110 | mem->next_free_chunk = mem->chunks[chunk_idx].next; |
108 | return &mem->blocks[chunk_idx * mem->block_size_bytes]; | 111 | return &mem->blocks[chunk_idx * mem->block_size_bytes]; |
109 | } else { | 112 | } else { |
113 | if (mem->trap) { | ||
114 | FAIL("Memory allocation failed, increase the allocator's capacity or " | ||
115 | "avoid fragmentation."); | ||
116 | } | ||
110 | return 0; // Large-enough free chunk not found. | 117 | return 0; // Large-enough free chunk not found. |
111 | } | 118 | } |
112 | } | 119 | } |
@@ -186,3 +193,8 @@ size_t mem_capacity_(const Memory* mem) { | |||
186 | assert(mem); | 193 | assert(mem); |
187 | return mem->num_blocks * mem->block_size_bytes; | 194 | return mem->num_blocks * mem->block_size_bytes; |
188 | } | 195 | } |
196 | |||
197 | void mem_enable_traps_(Memory* mem, bool enable) { | ||
198 | assert(mem); | ||
199 | mem->trap = enable; | ||
200 | } | ||