Many applications need lots of equally sized small memory blocks which have to be allocated and freed very fast.
Normally one would write some sort of pointer arithmetic or free list management, one for each structure, which splits superblocks into many small blocks. For simplicity these functions will not free any memory if not everything at a time, sometimes the capacity is limited.
The easy way is to use the GRAPE utility functions designed for this purpose. The following functions are a low level application of mem_alloc/mem_free implementing a configurable free list manager which will free unused superblocks if possible, at the only penalty of losing at most sizeof(void *) bytes per block.
You should call this function after having done a lot of memory operations.
An example using a private block memory manager, all blocks are freed with one function call at the end:
An example using the system wide standard block memory manager for this blocksize:{ void *bmm; struct my_struct *p[1000]; int i; bmm = g_bmm_new (sizeof (my_struct), 100); /* use manager */ for (i = 0; i < 1000; i++) p[i] = g_bmm_alloc (bmm); for (i = 0; i < 100; i++) g_bmm_free (bmm, p[i*10]); for (i = 0; i < 10; i++) p[i*100] = g_bmm_alloc (bmm); ... g_bmm_destroy (bmm); }
{ void *bmm; struct my_struct *p[1000]; int i; bmm = g_bmm_get_std (sizeof (my_struct)); /* use manager */ for (i = 0; i < 1000; i++) p[i] = g_bmm_alloc (bmm); ... for (i = 0; i < 1000; i++) g_bmm_free (bmm, p[i]); }
Copyright © by the Sonderforschungsbereich 256 at the Institut für Angewandte Mathematik, Universität Bonn.