Thad Smith wrote:
Grey Alien wrote:
>... I am currently alloc/dealloc small bits of memory (a struct)
several times during a programs lifecycle and I want to alloc memory
at prog start (say 5MB) so I don't have the overhead of malloc/free
(not to mention fragmentation). I can then request/release chunks from
the pool as and when necessary, during the prog lifecycle.
The simplest system is to work with fixed-size memory blocks. Break the
large block into several blocks of the desired size. When a block is
deallocated, link it into a list of free blocks, which is used to
allocate. No searching, no merging. You can write that in about 30
minutes -- some here, much less!
struct mempool_t
{
unsigned char * pool_ ;
unsigned int block_size ;
/* variable that keeps track of whether an element is free or not */
unsigned char * available ;
};
/**************/
/* Public API */
/**************/
/* Creates the pool, N elements of size item_size.
Returns 0 on success, 1 otherwise */
int mempool_create(struct mempool_t *pool,
const unsigned int num_elements,
const unsigned int item_size);
/* Requests mem chunk from pool, 0 ptr if no more mem
or rqst could not be fulfilled */
unsigned char * mempool_malloc(struct mempool_t *pool,
const unsigned int num_elements) ;
/* Requests zero-inited mem chunk from pool,
0 ptr if no more mem or rqst could not be fulfilled */
unsigned char * mempool_calloc(struct mempool_t *pool,
const unsigned int num_elements) ;
/* Requests mem chunk realloc from pool,
0 ptr if no more mem or rqst could not be fulfilled */
unsigned char * mempool_realloc(struct mempool_t *pool,
const unsigned int num_elements) ;
/* Requests mempool resize (expand only) 0 if succesful, 1 otherwise */
int mempool_resize(struct mempool_t **pool,
const unsigned int num_elements) ;
/* Local (static) functions */
int mempool_defrag(struct mempool_t * pool);