diff --git a/kernel/src/memory/Heap.cpp b/kernel/src/memory/Heap.cpp index fa663dce..3a2f4b67 100644 --- a/kernel/src/memory/Heap.cpp +++ b/kernel/src/memory/Heap.cpp @@ -125,8 +125,14 @@ static Option split(HeapBlock* block, usize size) static Result combine_forward(HeapBlock* block) { + // This block ends a memory range, cannot be combined with blocks outside its range. + if (block->status & BLOCK_END_MEM) return {}; + // The caller needs to ensure there is a next block. HeapBlock* const next = heap.next(block).value(); + // This block starts a memory range, cannot be combined with blocks outside its range. + if (next->status & BLOCK_START_MEM) return {}; + heap.remove(next); next->magic = BLOCK_DEAD; @@ -148,8 +154,13 @@ static Result combine_forward(HeapBlock* block) static Result combine_backward(HeapBlock* block) { + // This block starts a memory range, cannot be combined with blocks outside its range. + if (block->status & BLOCK_START_MEM) return block; + // The caller needs to ensure there is a last block. HeapBlock* const last = heap.previous(block).value(); + // This block ends a memory range, cannot be combined with blocks outside its range. + if (last->status & BLOCK_END_MEM) return block; heap.remove(block); block->magic = BLOCK_DEAD;