This commit is contained in:
Imbus 2025-08-12 03:25:05 +02:00
parent 4056473705
commit 86ffa5ef9d
4 changed files with 213 additions and 0 deletions

47
poolsclosed/simpe_pool.c Normal file
View file

@ -0,0 +1,47 @@
#include <malloc.h>
#include <string.h>
/* See: https://8dcc.github.io/programming/pool-allocator.html */
#define CHUNK_SIZE 64
typedef union Chunk Chunk;
union Chunk {
Chunk *next; // When not null, it is used
char arr[CHUNK_SIZE];
};
typedef struct Pool Pool;
struct Pool {
Chunk *free_chunk; // Pointer to a linked list of free chunks
Chunk *chunk_arr;
};
void *pool_alloc(Pool *pool) {
if (pool == NULL || pool->free_chunk == NULL)
return NULL;
// Pop a new one from the free list
Chunk *result = pool->free_chunk;
pool->free_chunk = pool->free_chunk->next;
return result;
}
void pool_free(Pool *pool, void *ptr) {
if (pool == NULL || ptr == NULL)
return;
// This can be done withuot an intermediate ptr
Chunk *freed = ptr;
freed->next = pool->free_chunk;
pool->free_chunk = freed;
}
void pool_close(Pool *pool) {
if (pool == NULL)
return;
free(pool->chunk_arr);
free(pool);
}