Memory Pools

Memory pools are often used to override default malloc() behaviour. Basic idea is that you allocate a larger pool of memory using malloc() or mmap(), then use it to give memory to program in smaller pieces using your preferred algorithm.

Memory pool doesn't have very strict definition, so there's many different kinds of pools used. One thing they have in common is that all the memory allocated from a specific pool can be immediately freed by freeing the pool itself.

Allocate Only Pool

This is a simple and fast pool. You can allocate memory from it but only way to free the memory is to free the whole pool. This is useful when you need to store lots of related data that doesn't change, for example function returning a structure with multiple variable sized fields.

struct alloc_only_pool {
	size_t alloc_size;
	size_t used_size; /* position where to allocate new data */
	void *data;
};

Fixed Size Pool

Fixed size pool allows allocation and freeing of elements with fixed size. Code is simple and fast. Useful if you need to create lots of objects with same size.

struct fixed_size_pool {
	size_t element_size;
	size_t element_count;
	size_t uninitialized_element_count; /* from the end */

	void *first_free_element; /* linked list of free()d elements */
	void *data;
};

Fully Featured Pool

Meaning a memory pool that is basically a full implementation of malloc() and free() that just operates with a smaller pool of memory.