Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Growing (and shrinking) memory pool

Let's say, for the purpose of the question, we have a memory pool that has n blocks allocated initially. However, when the capacity is reached, the pool wants to grow and become twice the size it was (2n).

Now this resize operation can be done with realloc in C, however the function itself may return a pointer to a different memory (with the old data copied in).

This means the pointers returned by the memory pool allocator may no longer be valid (since the memory may have been moved).

What would be a nice way to overcome this problem? Or is it even possible at all?


2 Answers

Allocate out of multiple non-contiguous pools of memory. When one pool is full, allocate a second pool, allowing it to be someplace else in your virtual address space.

Then the problem is one of keeping track of where your pools are. Typically you'd use some of the space in each pool for bookkeeping. For example, you might reserve one pointer's worth of space to keep a simple linear linked list of all the pools. More sophisticated allocators tend to require more bookkeeping overhead.

like image 151
Jamey Sharp Avatar answered Apr 29 '26 05:04

Jamey Sharp


Instead of using realloc, malloc a new/additional chunk of blocks (assuming there's no reason why the blocks, which are managed and returned and returned by your pool allocator, need to be in a single contiguous chunk of memory).

like image 35
ChrisW Avatar answered Apr 29 '26 06:04

ChrisW



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!