Expand description
Memory allocation APIs.
In a given program, the standard library has one “global” memory allocatorthat is used for example byBox<T> andVec<T>.
Currently the default global allocator is unspecified. Libraries, however,likecdylibs andstaticlibs are guaranteed to use theSystem bydefault.
§The#[global_allocator] attribute
This attribute allows configuring the choice of global allocator.You can use this to implement a completely custom global allocatorto route all1 default allocation requests to a custom object.
usestd::alloc::{GlobalAlloc, System, Layout};structMyAllocator;unsafe implGlobalAllocforMyAllocator {unsafe fnalloc(&self, layout: Layout) ->*mutu8 {unsafe{ System.alloc(layout) } }unsafe fndealloc(&self, ptr:*mutu8, layout: Layout) {unsafe{ System.dealloc(ptr, layout) } }}#[global_allocator]staticGLOBAL: MyAllocator = MyAllocator;fnmain() {// This `Vec` will allocate memory through `GLOBAL` aboveletmutv = Vec::new(); v.push(1);}The attribute is used on astatic item whose type implements theGlobalAlloc trait. This type can be provided by an external library:
The#[global_allocator] can only be used once in a crateor its recursive dependencies.
Note that the Rust standard library internals may stilldirectly call
Systemwhen necessary (for example for the runtimesupport typically required to implement a global allocator, seere-entrance onGlobalAllocfor more details). ↩
Structs§
- Layout
- Layout of a block of memory.
- Layout
Error - The
LayoutErroris returned when the parameters giventoLayout::from_size_alignor some otherLayoutconstructordo not satisfy its documented constraints. - System
- The default memory allocator provided by the operating system.
- Alloc
Error Experimental - The
AllocErrorerror indicates an allocation failurethat may be due to resource exhaustion or tosomething wrong when combining the given input arguments with thisallocator. - Global
Experimental - The global memory allocator.
Traits§
- Global
Alloc - A memory allocator that can be registered as the standard library’s defaultthrough the
#[global_allocator]attribute. - Allocator
Experimental - An implementation of
Allocatorcan allocate, grow, shrink, and deallocate arbitrary blocks ofdata described viaLayout.
Functions§
- alloc⚠
- Allocates memory with the global allocator.
- alloc_
zeroed ⚠ - Allocates zero-initialized memory with the global allocator.
- dealloc⚠
- Deallocates memory with the global allocator.
- handle_
alloc_ error - Signals a memory allocation error.
- realloc⚠
- Reallocates memory with the global allocator.
- set_
alloc_ error_ hook Experimental - Registers a custom allocation error hook, replacing any that was previously registered.
- take_
alloc_ error_ hook Experimental - Unregisters the current allocation error hook, returning it.
Type Aliases§
- Layout
Err Deprecated