Skip to content
chrishulbert edited this page May 19, 2011 · 1 revision

Example usage:

typedef struct {
int a, b, c;
} MyStruct;
#define MyStructFreer(x) // Nothing to free because MyStruct doesn't contain any pointers
KMEMPOOL_INIT (msp, MyStruct, MyStructFreer); // Sets up the macros
kmempool_t(msp) *myMemPool; // Declares a pointer to a mempool
myMemPool = kmp_init(msp); // Allocs the mempool
MyStruct *a, *b, *c; // Lets alloc some mystruct's
a = kmp_alloc(msp, myMemPool);
b = kmp_alloc(msp, myMemPool);
kmp_free(msp, myMemPool, a);
c = kmp_alloc(msp, myMemPool);
kmp_destroy(msp, myMemPool);

KMEMPOOLINIT name, kmptype_t, kmpfree_f

name is the list type name
kmptype_t is the type of what you're storing, eg MyStruct, NOT the pointer form MyStruct*
kmpfree_f is the macro to specially free any children of your MyStruct, it gets passed a MyStruct*
Note that your MyStruct* gets freed by the kmempool, if it doesn't contain any pointers then you wont need a kmpfree_f
Buf is like an array of pointers to MyStructs, eg MyStruct* listOfObjects[...]

The structure

typedef struct { 
size_t cnt, Number of items in use (eg number alloced - number freed/pooled) not used for anything
n, Number of items in the memory pool
max; Size of the buf array currently
kmptype_t **buf;
} kmp##name##_t;

The macros

#define kmempoolt(name) kmp##name##_t
Shortcut for the kmp_name_t struct typedef

#define kmpinit(name) kmp_init##name()
allocates memory and zeroes it out for a mempool and returns the pointer

#define kmpdestroy(name, mp) kmp_destroy##name(mp)
For each item, calls your custom free-er on it, passing the MyStruct*, as well as a normal free
Frees the buf
Frees the structure

#define kmpalloc(name, mp) kmp_alloc##name(mp)
Increments cnt (number of items allocated)
If the pool is empty, simply callocs an item and returns it using calloc(1, sizeof(kmptype_t));
Otherwise pulls the top one off the pool with mp->buf[--mp->n];

#define kmp_free(name, mp, p)
-- cnt (number of items allocated)
Adds p to the memory pool. P should be a pointer to your object, eg MyStruct*
Doubles max and reallocs the buf if necessary
Does mp->buf[mp->n++] = p;
Clone this wiki locally