我寫了一個池分配器的類,並用一些基本結構對它進行了測試,它似乎能夠正常工作。然而,當我用它來一個sf::Font
複製到分配的內存塊,我得到了以下錯誤:如何將sf :: Font複製到自定義池分配的內存中?
Exception thrown at 0x0F19009E (sfml-graphics-d-2.dll) in ChernoGame.exe: 0xC0000005: Access violation writing location 0xCDCDCDCD.
拋出此錯誤代碼:當我用這個sf::Texture
它工作正常
ResourceType *newResource = (ResourceType*)allocator.alloc();
ResourceType t;
*newResource = t; //error is thrown from here
,這個錯誤是隻有當我使用sf::Font
對於sf :: Font類的大小是76字節和對齊是4字節,我的分配器是跟隨此並分配一個76字節塊與4字節對齊,我可以不知道如何解決這個錯誤。
編輯:我試過它爲sf::SoundBuffer
它是拋出類似的錯誤。
池分配器初始化:
bool PoolAllocator::init(const unsigned int & numBlocks, const unsigned int & blockSize, const int&alignment)
{
if (mpMemoryBlock)
{
return false;
}
// assert(alignment & (alignment - 1) == 0);
auto expandedBlockSize = alignUp(blockSize, alignment);
mBlockSize = expandedBlockSize;
mAlignment = alignment;
mBlocks = numBlocks;
mpMemoryBlock = malloc((expandedBlockSize * numBlocks) + alignment);
if (!mpMemoryBlock)
{
return false;
}
auto currentBlock = alignUp((uintptr_t)mpMemoryBlock, alignment);
nextFreeBlock = currentBlock;
auto nextBlock = currentBlock;
mpActualBlock = (void*)currentBlock;
for (int i = 0; i < static_cast<int>(numBlocks); i++)
{
nextBlock = currentBlock + expandedBlockSize;
auto alignedForNextPointerStorage = alignUp(currentBlock, sizeof(uintptr_t));
*((uintptr_t*)alignedForNextPointerStorage) = nextBlock;
currentBlock = nextBlock;
}
auto alignedForNextPointerStorage = alignUp(currentBlock, sizeof(uintptr_t));
*((uintptr_t*)alignedForNextPointerStorage) = 0;
return true;
}
池分配器分配:
void * PoolAllocator::alloc()
{
if (*((uintptr_t*)nextFreeBlock) == 0)
{
return nullptr;
}
void *result = (void*)nextFreeBlock;
nextFreeBlock = *((uintptr_t*)alignUp(nextFreeBlock, sizeof(uintptr_t)));
return result;
}
池分配器釋放:
void PoolAllocator::dealloc(void* address)
{
auto nextPointer = alignUp((uintptr_t)address, sizeof(uintptr_t));
if ((alignUp((uintptr_t)address, mAlignment) == (uintptr_t)address) && (mpActualBlock <= address) && !((uintptr_t)address >= ((uintptr_t)mpActualBlock + (mBlocks * mBlockSize))))
{
*(uintptr_t*)nextPointer = nextFreeBlock;
nextFreeBlock = nextPointer;
}
else
{
throw std::runtime_error("Illegal deallocation of memory address : " + (uintptr_t)address);
}
}
你能不能展示你的課? –
你如何實際初始化這些實例?在我看來,就像你在跳過SFF的'sf :: Font'的構造函數一樣,只是施展你的記憶。許多SFML構造函數都是不重要的,因此您不能跳過它們。 – Mario
@Mario這就是爲什麼我創建ResourceType t並將其複製到分配的塊中,應該將默認構造對象t複製到newResource中的原因? –