Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

Memory Pool Attempt

yaser_aayaser_aa Member Posts: 1
Hello,

Am trying to build a memory pool for C++ objects of a certain type. The memory pool simply allocates a big chunk of memory at startup and manages a table of allocations from that chunk later on.

BTW, the pool is used in a multi-threading environment and I applied a lock to the allocation table on alloc / delete operations.

Also, if that's relevant, am using VC++.

However, it seems that I'm getting overlaps and corrupted objects when the memory pool is put to action, as if allocated objects are overlapping.

Below is the source code. Is there any flaw in it?

Help is so highly appreciated.

[color=Blue]template
class BaseAllocator
{
public:
virtual T * allocate(size_t nUnits) = 0;
virtual void free(T * ptr) = 0;
};

template
class FixedMemAllocator : public BaseAllocator
{
public:
FixedMemAllocator(size_t nInitCap)
{
// allocate the massive buffer
_pBuffer = (T *)(new char[nInitCap * sizeof(T) ]);

// initialize allocation table
_nFreeSlots = 0;
_pAllocTable = new T*[nInitCap];

T * pBufferItr = _pBuffer;

size_t i = 0;

// fill alloc table
while (i < nInitCap)
{
_pAllocTable[_nFreeSlots++] = pBufferItr;
pBufferItr++;
++i;
}
}

~FixedMemAllocator()
{
delete []_pAllocTable;
delete []_pBuffer;
}

virtual T * allocate(size_t nUnits)
{
assert(_nFreeSlots);
_TableMutex.lock();
T * ptr = _pAllocTable[--_nFreeSlots];
_TableMutex.unlock();

return ptr;
}

virtual void free(T * ptr)
{
_TableMutex.lock();
_pAllocTable[_nFreeSlots++] = ptr;
_TableMutex.unlock();
}

private:
T * * _pAllocTable;
T * _pBuffer;
size_t _nFreeSlots;

SyncObject _TableMutex;

void addBuffer();
};

// table mutex is the sync object (basically it wraps a critical section)[/color]
Sign In or Register to comment.