DevShiftTeam/AppShift-MemoryPool

could you tell how to allocate and free correct?

manuel76413 opened this issue · 1 comments

AppShift::Memory::MemoryPool * mp = new AppShift::Memory::MemoryPool(1<<20);
mp->dumpPoolData(); //dump message show current usage : 0% (0/1048576)

uint8_t * allocated[100] = { nullptr };
for (int j = 0; j < 100; j++) {
allocated[j] = mp->allocate<uint8_t>(1);
*allocated[j] = j;
}
mp->dumpPoolData(); //dump message show current usage : 0.162125% (1700/1048576)
for (int j = 0; j < 100; j++) {
mp->free(allocated[j]);
}
mp->dumpPoolData(); //dump message show current usage : 0.16053% (1700/1048576)
delete mp;

after call mp->free, though the usage still 0.16053%, not restore to 0,
could you tell me that why

Hi, thank you for opening an issue :)

The current reason that this doesn't works is that the pool moves its offset from which it allocates new data forward for any new allocation, and backwards only if the last allocated space is freed, if you free an element from the middle of the pool then it will not move its offset back, this is why the order of allocation in this version of the pool has meaning.

The memory pool frees its space when you deallocate in reverse order of your allocations, meaning that the deallocation part should run like so:

for (int j = 100; j > 0; --j) {
    mp->free(allocated[j]);
}

If you want to free all allocation made during a certain run, you can use a memory scope and this way destroy all the data and free the space without needing to free all the objects manually:

uint8_t * allocated[100] = { nullptr };
mp->startScope(); // Open a scope in the memory pool
for (int j = 0; j < 100; j++) {
    allocated[j] = mp->allocate<uint8_t>(1);
    *allocated[j] = j;
}
mp->dumpPoolData(); 

mp->endScope(); // Frees all allocations since the scope started
mp->dumpPoolData(); 

In the next version of the pool your code example will work as the pool will automatically determine that it should free the space, I already added this logic in the development branch.

Have a great day :)