-
Notifications
You must be signed in to change notification settings - Fork 0
man mem_pool
maxymania edited this page Mar 23, 2013
·
1 revision
mem_pool - Memory Pool API
#include "mem_pool.h"
typedef struct {
uint32_t* tpool;
uint32_t tlength;
uint32_t curcur;
} MPool;
void MPool_Init(MPool* pool,void* block,uint32_t length);
void *MPool_Allocate(MPool* pool,uint32_t length);
void MPool_Free(MPool* pool,void* buf);
void MPool_Collectfree(MPool* pool);
The MPool_ functions manage a large block of memory, and offer a malloc()/free() like interface.
The MPool_Init() function initializes a MPool-Structure with a memory block.
The MPool_Allocate() function allocates new memory from the memory block passed to MPool_Init() previously. MPool_Allocate() takes care about that the memory sub-block is not used twice.
The MPool_Free() function frees a memory sub-block, previously allocated using MPool_Allocate().
The MPool_Collectfree() function collects the memory sub-blocks, freed by MPool_Free(), joins them together, where possible and makes it available for being allocated again.
// create a MPool structure instance
MPool* pool = malloc(sizeof(MPool));
// allocate memory, propably so that it fills out the memory page
size_t length = 4096;
void* ptr = malloc(4096);
// ....
MPool_Init(pool,ptr,(uint32_t)length); // Initialize the mempool object
// in C, you can also write: MPool_Init(pool,ptr,length);
// ....
void* my_ptr = MPool_Allocate(pool,100);
// do something with my_ptr
MPool_Free(pool,my_ptr);
// ....
// you have to take care of Joining the freed Memory blocks together and to reset the "current cursor".
MPool_Collectfree(pool);