IMPORTANT: To view this page as Markdown, append `.md` to the URL (e.g. /docs/manual/basics.md). For the complete Mojo documentation index, see llms.txt.
Skip to main content
Version: Nightly
For the complete Mojo documentation index, see llms.txt. Markdown versions of all pages are available by appending .md to any URL (e.g. /docs/manual/basics.md).

alloc

def alloc[T: AnyType, /, *, alignment: Alignment = Alignment.of[T]()](layout: Layout[T, alignment=alignment], /) -> Allocation[T, alignment=alignment]

Allocates owned storage for len(layout) elements of T.

Returns an Allocation, an explicitly destroyed handle that bundles the newly allocated storage with its Layout. The compiler then enforces that the Allocation is destroyed on every path — by passing it to dealloc, or by explicitly leaking it with unsafe_leak().

When size_of[T]() == 0, this function returns a sentinel value.

Example:

from std.memory.alloc import alloc, dealloc, Layout

var allocation = alloc(Layout[Int32](length=4))
var ptr = allocation.unsafe_ptr()
for i in range(4):
ptr.unsafe_offset(i).write(i)
dealloc(allocation^)

Parameters:

  • ​T (AnyType): The type of the elements to allocate storage for.
  • ​alignment (Alignment): Byte alignment of the allocation, taken from layout.

Args:

Returns:

Allocation[T, alignment=alignment]: An Allocation owning the newly allocated, uninitialized storage.