Skip to main content

realloc

Function realloc 

Source
pub unsafe fn realloc(
    ptr: *mut u8,
    new_size: usize,
) -> Result<*mut u8, ReallocationError>
Expand description

Reallocates memory allocated by crate::alloc.

Mirrors C’s realloc:

  • realloc(null, new_size) is equivalent to crate::alloc(new_size).
  • realloc(ptr, 0) frees ptr and returns a null pointer.
  • Otherwise, the allocation is resized, in place when possible, and its contents are preserved up to the lesser of the old and new sizes. A new_size that rounds up to the allocation’s current total size returns ptr unchanged.

On success, the old pointer must be considered invalid: it must not be dereferenced or passed to crate::free or this function again. Only the returned pointer may be used.

§Errors

The old pointer remains valid whenever an error is returned.

  • AllocationError is returned if ptr is null and the allocation fails, or if new_size overflows the size computation or does not form a valid layout.
  • DeallocationError is returned if the size stored in the header does not form a valid layout, which signals memory corruption.
  • ImproperAlignment is returned if the pointer provided was not aligned properly.
  • MarkerFree is returned if ptr was previously freed or reallocated.
  • MarkerCorrupted is returned if the marker is neither free nor used, which generally signals memory corruption, or the passing of a pointer not allocated by crate::alloc.
  • NewAllocationFailed is returned if the allocator failed to resize the allocation.

§Safety

See crate::free for safety information. Additionally, best-effort detection of stale pointers after a successful realloc is only possible when the block has moved; after an in-place resize, the old pointer aliases the live allocation and misuse cannot be detected.