From 5775f9d224ced3e9d688c7223ab9a1de54a440eb Mon Sep 17 00:00:00 2001 From: Kevin Yonan Date: Sun, 28 Jul 2019 12:37:31 -0700 Subject: [PATCH] Patched potential bug when defragging. (#920) * Patched potential bug when defragging. Patched a potential bug concerning the '__RemoveNode' function as, when removing certain nodes that are either at the head or tail, it can yield a free list node of size 0 bug as the previous node was removed and its size was set to 0 but not fully removed from the other nodes. * A few more potential bug patches. --- src/rmem.h | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/src/rmem.h b/src/rmem.h index 65e08194..439b3039 100644 --- a/src/rmem.h +++ b/src/rmem.h @@ -164,10 +164,19 @@ static inline size_t __AlignSize(const size_t size, const size_t align) return (size + (align - 1)) & -align; } -static void __RemoveNode(MemNode **const node) +static void __RemoveNode(MemPool *const mempool, MemNode **const node) { - ((*node)->prev != NULL)? ((*node)->prev->next = (*node)->next) : (*node = (*node)->next); - ((*node)->next != NULL)? ((*node)->next->prev = (*node)->prev) : (*node = (*node)->prev); + if ((*node)->prev != NULL) (*node)->prev->next = (*node)->next; + else { + mempool->freeList.head = (*node)->next; + mempool->freeList.head->prev = NULL; + } + + if ((*node)->next != NULL) (*node)->next->prev = (*node)->prev; + else { + mempool->freeList.tail = (*node)->prev; + mempool->freeList.tail->next = NULL; + } } //---------------------------------------------------------------------------------- @@ -242,7 +251,7 @@ void *MemPoolAlloc(MemPool *const mempool, const size_t size) { // Close in size - reduce fragmentation by not splitting. new_mem = *inode; - __RemoveNode(inode); + __RemoveNode(mempool, inode); mempool->freeList.len--; new_mem->next = new_mem->prev = NULL; break; @@ -427,7 +436,7 @@ bool MemPoolDefrag(MemPool *const mempool) // If node is right at the stack, merge it back into the stack. mempool->stack.base += (*node)->size; (*node)->size = 0UL; - __RemoveNode(node); + __RemoveNode(mempool, node); mempool->freeList.len--; node = &mempool->freeList.head; } @@ -475,6 +484,7 @@ bool MemPoolDefrag(MemPool *const mempool) (*node)->size = 0UL; (*node)->next->prev = (*node)->prev; (*node)->prev->next = (*node)->next; + *node = (*node)->next; mempool->freeList.len--; node = &mempool->freeList.head; @@ -487,6 +497,7 @@ bool MemPoolDefrag(MemPool *const mempool) (*node)->size = 0UL; (*node)->next->prev = (*node)->prev; (*node)->prev->next = (*node)->next; + *node = (*node)->prev; mempool->freeList.len--; node = &mempool->freeList.head;