龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > 软件开发 > C/C++开发 >

简明分析C/C++内存分配的解决方案(4)

时间:2009-12-22 15:42来源:未知 作者:admin 点击:
分享到:
unsigned int CMemoryPool::CalculateNeededChunks(const std::size_t return ((unsigned int) ceil(f)); } std::size_t CMemoryPool::CalculateBestMemoryBlockSize(const std::size_t return std::size_t((uiNeede

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)

{

精彩图集

赞助商链接