Skip to content

Commit a51e890

Browse files
committed
Fix incorrect attempted merging at maximum order
<co-authored by Tom Spink tspink@gmail.com>
1 parent f225090 commit a51e890

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

src/lib.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,8 @@ impl<const ORDER: usize> Heap<ORDER> {
157157
// Merge free buddy lists
158158
let mut current_ptr = ptr.as_ptr() as usize;
159159
let mut current_class = class;
160-
while current_class < self.free_list.len() {
160+
161+
while current_class < self.free_list.len() - 1 {
161162
let buddy = current_ptr ^ (1 << current_class);
162163
let mut flag = false;
163164
for block in self.free_list[current_class].iter_mut() {

src/test.rs

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,3 +192,34 @@ fn test_frame_allocator_aligned() {
192192
Some(16)
193193
);
194194
}
195+
196+
#[test]
197+
fn test_heap_merge_final_order() {
198+
const NUM_ORDERS: usize = 5;
199+
200+
let backing_size = 1 << NUM_ORDERS;
201+
let backing_layout = Layout::from_size_align(backing_size, backing_size).unwrap();
202+
203+
// create a new heap with 5 orders
204+
let mut heap = Heap::<NUM_ORDERS>::new();
205+
206+
// allocate host memory for use by heap
207+
let backing_allocation = unsafe { std::alloc::alloc(backing_layout) };
208+
209+
let start = backing_allocation as usize;
210+
let middle = unsafe { backing_allocation.add(backing_size / 2) } as usize;
211+
let end = unsafe { backing_allocation.add(backing_size) } as usize;
212+
213+
// add two contiguous ranges of memory
214+
unsafe { heap.add_to_heap(start, middle) };
215+
unsafe { heap.add_to_heap(middle, end) };
216+
217+
// NUM_ORDERS - 1 is the maximum order of the heap
218+
let layout = Layout::from_size_align(1 << (NUM_ORDERS - 1), 1).unwrap();
219+
220+
// allocation should succeed, using one of the added ranges
221+
let alloc = heap.alloc(layout).unwrap();
222+
223+
// deallocation should not attempt to merge the two contiguous ranges as the next order does not exist
224+
heap.dealloc(alloc, layout);
225+
}

0 commit comments

Comments
 (0)