Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdbool.h>
- #include "mem_pool.h"
- typedef struct block Block;
- typedef struct block
- {
- Block *next;
- void *ptr;
- bool free;
- } Block;
- struct mem_pool
- {
- Block *head;
- void *memory;
- size_t memory_size;
- size_t memb_size;
- };
- #define get_ptr_and_increase(pool, size) pool->memory; pool->memory += size
- #define add_block_size(pool) pool->memory_size += sizeof(Block) + pool->memb_size
- /**
- * Creates an internal representation of a memory block
- */
- static Block *new_block(MemoryPool *pool, bool is_free)
- {
- Block *block = get_ptr_and_increase(pool, sizeof(Block));
- block->ptr = get_ptr_and_increase(pool, pool->memb_size);
- block->next = NULL;
- block->free = is_free;
- return block;
- }
- /**
- * Initializes the pool with the given size of members
- */
- MemoryPool *pool_init(size_t memb_size)
- {
- MemoryPool *pool = malloc(sizeof(MemoryPool));
- pool->memb_size = memb_size;
- pool->memory_size = 0;
- add_block_size(pool);
- pool->memory = malloc(pool->memory_size);
- pool->head = new_block(pool, true);
- return pool;
- }
- /**
- * Internally looks for the first free Block
- */
- static Block *find_free(MemoryPool *pool)
- {
- Block *current = pool->head;
- while (NULL != current && false == current->free) {
- current = current->next;
- }
- return current;
- }
- /**
- * Adds a new Block to the beginning of the list if no other block is free
- */
- static void add_new_head(MemoryPool *pool)
- {
- Block *tmp = pool->head;
- pool->head = new_block(pool, false);
- pool->head->next = tmp;
- add_block_size(pool);
- pool->memory = realloc(pool->memory, pool->memory_size);
- }
- /**
- * Finds or creates a new Block, but only returns the void pointer to the user
- */
- void *pool_alloc(MemoryPool *pool)
- {
- Block *free = find_free(pool);
- if (NULL != free) {
- return free->ptr;
- }
- add_new_head(pool);
- return pool->head->ptr;
- }
- /**
- * Sets the block free, thus alloweing the pool the give it to the user again
- */
- void pool_free(MemoryPool *pool, void *block)
- {
- Block *current = pool->head;
- while (current->ptr != block) {
- current = current->next;
- }
- current->free = true;
- }
- void pool_destroy(MemoryPool *pool)
- {
- free(pool->memory - pool->memory_size);
- free(pool);
- }
Advertisement
Add Comment
Please, Sign In to add comment