Skip to main content

realloc

Function realloc 

1.28.0 · Source
pub unsafe fn realloc(ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8
Expand description

Reallocates memory with the global allocator.

This function forwards calls to the GlobalAlloc::realloc 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::realloc 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 pointer passed to this function must have been obtained by invoking alloc, alloc_zeroed, or realloc. In particular, passing a pointer returned by the underlying methods on GlobalAlloc is not permitted.
  • 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 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).
  • If this grows the allocation, the contents of the grown part of the new allocation allocation are de-initialized by this function before returning.
  • If this shrinks the allocation, the contents of the removed part of the old allocation are de-initialized by this function before invoking the underlying allocator.

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

§Safety

See GlobalAlloc::realloc.