PacktPublishing / Building-Low-Latency-Applications-with-CPP

Building Low Latency Applications with CPP by Packt Publishing

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Random allocate and deallocate objects in memory pool in chapter 4?

yt7589 opened this issue · comments

I want to know how to deal with randomly allocate and deallocate in in memory pool in chapter 4. For example, I initialized a memory pool with initial size is 10. Then I allocate six objects. The memory pool will look as bellow:

index object_ is_free_
0 o1 false
1 o2 false
2 o3 false
3 o4 false
4 o5 false
5 o6 false
6 empty true
7 empty true
8 empty true
9 empty true

Then I deallocated the 3rd and 5th elements as bellow:

index object_ is_free_
0 o1 false
1 o2 false
2 empty true
3 o4 false
4 empty true
5 o6 false
6 empty true
7 empty true
8 empty true
9 empty true

If I allocate 4 objects it would as bellow:

index object_ is_free_
0 o1 false
1 o2 false
2 empty true
3 o4 false
4 empty true
5 o6 false
6 o7 false
7 o8 false
8 o9 false
9 o10 false

The the memory pool is full now. But it's 2, 4 index position is free. It the memory pool is large it will left many holes.

My question is:

  1. Is my understanding is right or not?
  2. If my understanding is right how to solve this problem?

Hey!

  1. Yes I think that's right; memory fragmentation will occur and allocating an object is worst case linear time complexity (but will very often be faster than that). You can rewrite or tune the "find next free index" method to meet the needs of your application
    and
  2. The allocation method returns the new object's pointer so it's up to the program to keep track of it, therefore it is kind of random access by design and I'm not sure making the objects all contiguously allocated is where the benefit of the data structure shines through

It seems to me the benefit of a memory pool in this particular case is avoiding the runtime cost of dynamic memory allocations, and having a reserved block of memory to allocate from on either the stack or the heap of the system. This way, that area of the heap or stack isn't being polluted by other applications on the system and remains relatively static as far as the OS is concerned. In other words we're not so much looking for the blocks to all be cached and avoid fragmentation here, unless we know we'll rarely be modifying the objects.