Skip to main content

alloc_zeroed

Function alloc_zeroed 

1.28.0 · Source
pub unsafe fn alloc_zeroed(layout: Layout) -> *mut u8
Expand description

Allocates zero-initialized memory with the global allocator.

This function forwards calls to the GlobalAlloc::alloc_zeroed 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_zeroed 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.
  • The allocation can only be freed by invoking dealloc or realloc. In particular, passing a pointer to such an allocation directly to the underlying method on GlobalAlloc is 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).
  • 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.

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_zeroed method of the Global type when it and the Allocator trait become stable.

§Safety

See GlobalAlloc::alloc_zeroed.

§Examples

use std::alloc::{alloc_zeroed, dealloc, handle_alloc_error, Layout};

unsafe {
    let layout = Layout::new::<u16>();
    let ptr = alloc_zeroed(layout);
    if ptr.is_null() {
        handle_alloc_error(layout);
    }

    assert_eq!(*(ptr as *mut u16), 0);

    dealloc(ptr, layout);
}