alloc_system -

# `alloc_system`

The tracking issue for this feature is: #32838

See also `global_allocator`.

The compiler currently ships two default allocators: `alloc_system` and `alloc_jemalloc` (some targets don't have jemalloc, however). These allocators are normal Rust crates and contain an implementation of the routines to allocate and deallocate memory. The standard library is not compiled assuming either one, and the compiler will decide which allocator is in use at compile-time depending on the type of output artifact being produced.

Binaries generated by the compiler will use `alloc_jemalloc` by default (where available). In this situation the compiler "controls the world" in the sense of it has power over the final link. Primarily this means that the allocator decision can be left up the compiler.

Dynamic and static libraries, however, will use `alloc_system` by default. Here Rust is typically a 'guest' in another application or another world where it cannot authoritatively decide what allocator is in use. As a result it resorts back to the standard APIs (e.g. `malloc` and `free`) for acquiring and releasing memory.

# Switching Allocators

Although the compiler's default choices may work most of the time, it's often necessary to tweak certain aspects. Overriding the compiler's decision about which allocator is in use is done through the `#[global_allocator]` attribute:

    #![feature(alloc_system, global_allocator, allocator_api)]

    extern crate alloc_system;

    use alloc_system::System;

    #[global_allocator]
    static A: System = System;

    fn main() {
        let a = Box::new(4); // Allocates from the system allocator.
        println!("{}", a);
    }

In this example the binary generated will not link to jemalloc by default but instead use the system allocator. Conversely to generate a dynamic library which uses jemalloc by default one would write:

(The `alloc_jemalloc` crate cannot be used to control the global allocator, crate.io’s `jemallocator` crate provides equivalent functionality.)

    # Cargo.toml
    [dependencies]
    jemallocator = "0.1"

    #![feature(global_allocator)]
    #![crate_type = "dylib"]

    extern crate jemallocator;

    #[global_allocator]
    static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc;

    pub fn foo() {
        let a = Box::new(4); // Allocates from jemalloc.
        println!("{}", a);
    }
    # fn main() {}