Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Attributes

The #[global_allocator] attribute

Reference for #[global_allocator]: register a static GlobalAlloc implementation to count, limit or replace every heap allocation in a Rust program.

Every Box, Vec, String and Rc in a Rust program gets its memory from one global allocator. By default that is the system allocator (malloc and free on most platforms). The #[global_allocator] attribute lets you register a different one, for example to count allocations, enforce a memory limit, or use a specialised allocator such as jemalloc or mimalloc (through crates).

You put the attribute on a static whose type implements the unsafe trait std::alloc::GlobalAlloc. A program can have at most one.

Rust
use std::alloc::System;

#[global_allocator]
static ALLOC: System = System;

Try it

Rust Counting allocated bytes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust Refusing large allocations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Syntax

Rust
#[global_allocator]
static NAME: AllocatorType = AllocatorType /* value */;
Rust
pub unsafe trait GlobalAlloc {
    unsafe fn alloc(&self, layout: Layout) -> *mut u8;
    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout);
    unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { /* default */ }
    unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { /* default */ }
}
Method Description
alloc Returns a pointer to a block that fits layout, or null on failure.
dealloc Frees a block previously returned by this allocator with the same layout.
alloc_zeroed Like alloc but zero-filled; default calls alloc then writes zeros.
realloc Resizes a block; default allocates, copies and frees.

Returns and edge cases: returning null from alloc means failure; callers then run the out-of-memory handler (infallible APIs abort the process), while try_reserve and similar report an error instead.

Usage notes

  • The trait is unsafe: the allocator must never unwind, must return correctly aligned memory, and must not hand out the same live block twice.
  • Never allocate inside alloc. A println!, Vec or String inside the allocator calls the allocator again and recurses or deadlocks. Use atomics and raw writes only.
  • The static must be Sync, because every thread uses it; atomics make counters safe.
  • #[global_allocator] can be placed only in an executable-level decision: libraries should not set it, since the final program can have only one.
  • System is the default allocator type; wrapping it, as above, is the usual way to add behavior without writing a memory manager.
  • Collections also have per-container allocators behind the unstable Allocator API; #[global_allocator] is the stable route.
  • Allocations can happen before main starts (runtime setup), so counters rarely start at zero.
  • Because the counters include allocations made by println!, measure by taking differences around code that does not print.