]> git.lizzy.rs Git - rust.git/blob - src/doc/unstable-book/src/library-features/alloc-system.md
add -Z pre-link-arg{,s} to rustc
[rust.git] / src / doc / unstable-book / src / library-features / alloc-system.md
1 # `alloc_system`
2
3 The tracking issue for this feature is: [#33082]
4
5 [#33082]: https://github.com/rust-lang/rust/issues/33082
6
7 See also [`alloc_jemalloc`](alloc-jemalloc.html).
8
9 ------------------------
10
11 The compiler currently ships two default allocators: `alloc_system` and
12 `alloc_jemalloc` (some targets don't have jemalloc, however). These allocators
13 are normal Rust crates and contain an implementation of the routines to
14 allocate and deallocate memory. The standard library is not compiled assuming
15 either one, and the compiler will decide which allocator is in use at
16 compile-time depending on the type of output artifact being produced.
17
18 Binaries generated by the compiler will use `alloc_jemalloc` by default (where
19 available). In this situation the compiler "controls the world" in the sense of
20 it has power over the final link. Primarily this means that the allocator
21 decision can be left up the compiler.
22
23 Dynamic and static libraries, however, will use `alloc_system` by default. Here
24 Rust is typically a 'guest' in another application or another world where it
25 cannot authoritatively decide what allocator is in use. As a result it resorts
26 back to the standard APIs (e.g. `malloc` and `free`) for acquiring and releasing
27 memory.
28
29 # Switching Allocators
30
31 Although the compiler's default choices may work most of the time, it's often
32 necessary to tweak certain aspects. Overriding the compiler's decision about
33 which allocator is in use is done simply by linking to the desired allocator:
34
35 ```rust,no_run
36 #![feature(alloc_system)]
37
38 extern crate alloc_system;
39
40 fn main() {
41     let a = Box::new(4); // Allocates from the system allocator.
42     println!("{}", a);
43 }
44 ```
45
46 In this example the binary generated will not link to jemalloc by default but
47 instead use the system allocator. Conversely to generate a dynamic library which
48 uses jemalloc by default one would write:
49
50 ```rust,ignore
51 #![feature(alloc_jemalloc)]
52 #![crate_type = "dylib"]
53
54 extern crate alloc_jemalloc;
55
56 pub fn foo() {
57     let a = Box::new(4); // Allocates from jemalloc.
58     println!("{}", a);
59 }
60 # fn main() {}
61 ```
62