pub unsafe fn alloc(layout: Layout) -> *mut u8Expand description
Allocates memory with the global allocator.
This function forwards calls to the GlobalAlloc::alloc method
of the allocator registered with the #[global_allocator] attribute
if there is one, or the std crate’s default.
Note, however, that invoking this function is not equivalent to invoking the underlying
GlobalAlloc::alloc method of the registered allocator directly. Users of this function
cannot assume anything about what the allocator does, other than the documented requirements.
This means:
- This function may non-deterministically entirely skip the underlying allocator, e.g. if the compiler can show that this allocation can be replaced by a stack variable. The compiler may also merge multiple allocation operations into one, as long as it can also adjust all corresponding deallocation operations accordingly.
- An allocation created by invoking this function has exactly the size and minimum alignment
defined by
layout, even if the underlying allocator makes stronger promises. - The allocation can only be freed by invoking
deallocorrealloc. In particular, passing a pointer to such an allocation directly to the underlying method onGlobalAllocis not permitted. Until one of those functions is called, it is undefined behavior to access the memory that backs this allocation with any pointer not derived from the return value of this function (e.g., with internal pointers the allocator might keep around). - This function de-initializes the contents of the allocation before handing it to the user. So even if you control the underlying allocator and know that it explicitly initialized this memory, you cannot rely on it being initialized.
Users of this function have to consider that in the future, allocators may be allowed to unwind.
This function is expected to be deprecated in favor of the allocate method
of the Global type when it and the Allocator trait become stable.
§Safety
See GlobalAlloc::alloc.