How to Write a Custom Allocator in Rust

Implement the GlobalAlloc trait and apply the #[global_allocator] attribute to a static struct to replace Rust's default memory allocator.

You write a custom allocator in Rust by implementing the GlobalAlloc trait and using the #[global_allocator] attribute on a static instance. This replaces the default system allocator for your entire binary.

use std::alloc::{GlobalAlloc, Layout, System};
use std::sync::atomic::{AtomicBool, Ordering};

static MY_ALLOCATOR: MyAllocator = MyAllocator;

struct MyAllocator;

unsafe impl GlobalAlloc for MyAllocator {
    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
        System.alloc(layout)
    }

    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
        System.dealloc(ptr, layout)
    }
}

#[global_allocator]
static GLOBAL: MyAllocator = MyAllocator;

fn main() {
    println!("Custom allocator active");
}