From fd47a98d571f44fd716a4b517d507946eae4d16f Mon Sep 17 00:00:00 2001 From: niu2x Date: Sun, 18 Jul 2021 22:43:49 +0800 Subject: [PATCH] freelist allcoator bugfix 1. when allocate memory: if rest < sizeof(Node), it should not insert to free list. 2. when free memory: a. if free list head is nullptr, we should set head ptr. b. free node ptr should offset padding bytes. --- src/FreeListAllocator.cpp | 32 ++++++++++++++++++++++---------- 1 file changed, 22 insertions(+), 10 deletions(-) diff --git a/src/FreeListAllocator.cpp b/src/FreeListAllocator.cpp index fb84853..9f05ad1 100644 --- a/src/FreeListAllocator.cpp +++ b/src/FreeListAllocator.cpp @@ -44,9 +44,15 @@ void* FreeListAllocator::Allocate(const std::size_t size, const std::size_t alig const std::size_t alignmentPadding = padding - allocationHeaderSize; - const std::size_t requiredSize = size + padding; + std::size_t requiredSize = size + padding; + + std::size_t rest = affectedNode->data.blockSize - requiredSize; + + if (rest && rest < sizeof(Node)) { + requiredSize += rest; + rest = 0; + } - const std::size_t rest = affectedNode->data.blockSize - requiredSize; if (rest > 0) { // We have to split the block into the data block and a free block of size 'rest' @@ -126,21 +132,27 @@ void FreeListAllocator::Free(void* ptr) { const std::size_t headerAddress = currentAddress - sizeof (FreeListAllocator::AllocationHeader); const FreeListAllocator::AllocationHeader * allocationHeader{ (FreeListAllocator::AllocationHeader *) headerAddress}; - Node * freeNode = (Node *) (headerAddress); - freeNode->data.blockSize = allocationHeader->blockSize + allocationHeader->padding; + Node *freeNode = (Node *)(headerAddress - allocationHeader->padding); + freeNode->data.blockSize = allocationHeader->blockSize; freeNode->next = nullptr; Node * it = m_freeList.head; Node * itPrev = nullptr; - while (it != nullptr) { - if (ptr < it) { - m_freeList.insert(itPrev, freeNode); - break; + + if (!it) { + m_freeList.head = freeNode; + } else { + while (it != nullptr) { + if (ptr < it) { + m_freeList.insert(itPrev, freeNode); + break; + } + itPrev = it; + it = it->next; } - itPrev = it; - it = it->next; } + m_used -= freeNode->data.blockSize; // Merge contiguous nodes