diff --git a/include/malloc_from_scratch/memory_internal.h b/include/malloc_from_scratch/memory_internal.h index e72a982..8de6bcb 100644 --- a/include/malloc_from_scratch/memory_internal.h +++ b/include/malloc_from_scratch/memory_internal.h @@ -18,6 +18,7 @@ struct MemoryBlock }; inline MemoryBlock* block_list_head = nullptr; +inline MemoryBlock* block_list_tail = nullptr; inline void* heap_start = nullptr; inline size_t total_memory_allocated = 0; inline pthread_mutex_t allocator_mutex = PTHREAD_MUTEX_INITIALIZER; diff --git a/src/free.cpp b/src/free.cpp index 396d21f..8c516b5 100644 --- a/src/free.cpp +++ b/src/free.cpp @@ -48,10 +48,12 @@ void free(void* ptr) if (block_previous_from_last != nullptr) { block_previous_from_last->next_ = nullptr; + internal::block_list_tail = block_previous_from_last; } else { internal::block_list_head = nullptr; + internal::block_list_tail = nullptr; } internal::decreaseHeap(block_list_tail); } diff --git a/src/malloc.cpp b/src/malloc.cpp index e5d7827..f6ea3af 100644 --- a/src/malloc.cpp +++ b/src/malloc.cpp @@ -144,18 +144,17 @@ void* getMemoryBlockSplitAddress(MemoryBlock* new_block, size_t size) void insertMemoryBlockAtEnd(MemoryBlock** block_list_head, MemoryBlock* new_block) { + new_block->next_ = nullptr; + if (*block_list_head == nullptr) { *block_list_head = new_block; + block_list_tail = new_block; } else { - MemoryBlock* current = *block_list_head; - while (current->next_ != nullptr) - { - current = current->next_; - } - current->next_ = new_block; + block_list_tail->next_ = new_block; + block_list_tail = new_block; } }