Question

Is it possible to create a memory pool implementation that follows the simple logic:

1 - Allocate n bytes worth of memory pool.

2 - Use modified new(); function/operator that does not allocate memory only gets a pointer to the beginning of the memory pool. This way objects are created dynamically without overhead.

3 - When the memory pool runs low, it deallocates what is left of it and allocates a new memory pool

4 - the objects created in the first memory pool are left to pick up the memory based on their sizes. The difference of what was allocated in the first pool and what was given back when it ran low is restored by the objects upon their deletion.

My worries are mainly about the fact that I have no idea how to delete the memory pool smaller than it was allocated, KEEPING IN MIND that besides what is left in the end of the memory pool object there is also a OS header for the memory pool that is before the first object, allocated in the pool. What approach do I need to make sure no memory is leaked, that deleting the excess memory pool won't delete objects that are allocated in it and that the header for the memory pool fragment is safely removed.

Thanks!

EDIT: Note that the intent is for memory to be allocated by the memory pool and released by the objects, which may have different lifetime. If this is possible at all...

Was it helpful?

Solution

Firstly, this sounds like an arena allocator (as mentioned in the comments), if you want to know what you should be searching for.

Note that arenas are only really useful if you plan to tear down the whole thing at once; if you expect to reclaim memory from deleted objects for re-use, you end up writing your own heap sitting on top of the arena. If you just want to keep the arena-chunk alive until the last object is deallocated, you can manage with a refcount.

Secondly, the only common way I know to allocate memory which you can later shrink without possibly moving (like realloc), is using memory maps: this is platform-specific.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top