Global allocators

Minimum Rust version: 1.28

Allocators are the way that programs in Rust obtain memory from the system atruntime. Previously, Rust did not allow changing the way memory is obtained,which prevented some use cases. On some platforms, this meant using jemalloc,on others, the system allocator, but there was no way for users to controlthis key component. With 1.28.0, the #[global_allocator] attribute is nowstable, which allows Rust programs to set their allocator to the systemallocator, as well as define new allocators by implementing the GlobalAlloctrait.

The default allocator for Rust programs on some platforms is jemalloc. Thestandard library now provides a handle to the system allocator, which can beused to switch to the system allocator when desired, by declaring a staticand marking it with the #[global_allocator] attribute.

  1. use std::alloc::System;
  2. #[global_allocator]
  3. static GLOBAL: System = System;
  4. fn main() {
  5. let mut v = Vec::new();
  6. // This will allocate memory using the system allocator.
  7. v.push(1);
  8. }

However, sometimes you want to define a custom allocator for a givenapplication domain. This is also relatively easy to do by implementing theGlobalAlloc trait. You can read more about how to do this in thedocumentation.