Skip to content

Commit ac23bcd

Browse files
committed
test using the Global allocator trait to alloc/free a Box
1 parent 724be29 commit ac23bcd

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

tests/run-pass/heap_system.rs renamed to tests/run-pass/heap_allocator.rs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
//ignore-windows: Inspects allocation base address on Windows
22
#![feature(allocator_api)]
33

4+
use std::ptr::NonNull;
45
use std::alloc::{Global, Alloc, Layout, System};
56

67
fn check_overalign_requests<T: Alloc>(mut allocator: T) {
@@ -23,7 +24,31 @@ fn check_overalign_requests<T: Alloc>(mut allocator: T) {
2324
}
2425
}
2526

27+
fn global_to_box() {
28+
type T = [i32; 4];
29+
let l = Layout::new::<T>();
30+
// allocate manually with global allocator, then turn into Box and free there
31+
unsafe {
32+
let ptr = Global.alloc(l).unwrap().as_ptr() as *mut T;
33+
let b = Box::from_raw(ptr);
34+
drop(b);
35+
}
36+
}
37+
38+
fn box_to_global() {
39+
type T = [i32; 4];
40+
let l = Layout::new::<T>();
41+
// allocate with the Box, then deallocate manually with global allocator
42+
unsafe {
43+
let b = Box::new(T::default());
44+
let ptr = Box::into_raw(b);
45+
Global.dealloc(NonNull::new(ptr as *mut u8).unwrap(), l);
46+
}
47+
}
48+
2649
fn main() {
2750
check_overalign_requests(System);
2851
check_overalign_requests(Global);
52+
global_to_box();
53+
box_to_global();
2954
}

0 commit comments

Comments
 (0)