简明分析C/C++内存分配的解决方案(4)
unsigned int CMemoryPool::CalculateNeededChunks(const std::size_t &sMemorySize)
{
float f = (float) (((float)sMemorySize) / ((float)m_sMemoryChunkSize));
return ((unsigned int) ceil(f));
}
std::size_t CMemoryPool::CalculateBestMemoryBlockSize(const std::size_t &sRequestedMemoryBlockSize)
{
unsigned int uiNeededChunks = CalculateNeededChunks(sRequestedMemoryBlockSize);
return std::size_t((uiNeededChunks * m_sMemoryChunkSize));
}
bool CMemoryPool::LinkChunksToData(SMemoryChunk* ptrNewChunks, unsigned int uiChunkCount, TByte* ptrNewMemBlock)
{
SMemoryChunk *ptrNewChunk = NULL;
unsigned int uiMemOffSet = 0;
bool bAllocationChunkAssigned = false ;
for(unsigned int i = 0; i < uiChunkCount; i++)
{
//建立链表
if(!m_ptrFirstChunk)
{
m_ptrFirstChunk = SetChunkDefaults(&(ptrNewChunks[0]));
m_ptrLastChunk = m_ptrFirstChunk;
m_ptrCursorChunk = m_ptrFirstChunk;
}
else
{
ptrNewChunk = SetChunkDefaults(&(ptrNewChunks[i]));
m_ptrLastChunk->Next = ptrNewChunk;
m_ptrLastChunk = ptrNewChunk;
}
//根据块(Chunk)的大小计算下一块的内存偏移地址
uiMemOffSet = (i * ((unsigned int) m_sMemoryChunkSize));
//结点指向内存偏移地址
m_ptrLastChunk->Data = &(ptrNewMemBlock[uiMemOffSet]);
if(!bAllocationChunkAssigned)
{
m_ptrLastChunk->IsAllocationChunk = true;
bAllocationChunkAssigned = true;
}
}
return RecalcChunkMemorySize(m_ptrFirstChunk, m_uiMemoryChunkCount);
}
bool CMemoryPool::RecalcChunkMemorySize(SMemoryChunk *ptrChunk, unsigned int uiChunkCount)
{
unsigned int uiMemOffSet = 0 ;
for(unsigned int i = 0; i < uiChunkCount; i++)
{
if(ptrChunk)
{
uiMemOffSet = (i * ((unsigned int) m_sMemoryChunkSize)) ;
ptrChunk->DataSize = (((unsigned int) m_sTotalMemoryPoolSize) - uiMemOffSet);
ptrChunk = ptrChunk->Next ;
}
else
{
assert(false && "Error : ptrChunk == NULL");
return false;
}
}
return true;
}
SMemoryChunk* CMemoryPool::SetChunkDefaults(SMemoryChunk* ptrChunk)
{