summaryrefslogtreecommitdiff
path: root/src/tools/miri/tests/pass/global_allocator.rs
blob: 24a56c663f06079bb220cc328bb1cb141aa7bf58 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#![feature(allocator_api, slice_ptr_get)]

use std::alloc::{Allocator as _, Global, GlobalAlloc, Layout, System};

#[global_allocator]
static ALLOCATOR: Allocator = Allocator;

struct Allocator;

unsafe impl GlobalAlloc for Allocator {
    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
        // use specific size to avoid getting triggered by rt
        if layout.size() == 123 {
            println!("Allocated!")
        }

        System.alloc(layout)
    }

    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
        if layout.size() == 123 {
            println!("Dellocated!")
        }

        System.dealloc(ptr, layout)
    }
}

fn main() {
    // Only okay because we explicitly set a global allocator that uses the system allocator!
    let l = Layout::from_size_align(123, 1).unwrap();
    let ptr = Global.allocate(l).unwrap().as_non_null_ptr(); // allocating with Global...
    unsafe {
        System.deallocate(ptr, l);
    } // ... and deallocating with System.

    let ptr = System.allocate(l).unwrap().as_non_null_ptr(); // allocating with System...
    unsafe {
        Global.deallocate(ptr, l);
    } // ... and deallocating with Global.
}