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[type: AnyType, /](count: Int, *, alignment: Int = Int((get_alignof type, _current_target()))) -> Pointer[type, MutUntrackedOrigin]
Allocates contiguous storage for count elements of type with alignment alignment.
Deprecated: alloc without a Layout is deprecated, use the Layout-based alloc instead; as a temporary migration step, use unsafe_alloc
Parameters:
- type (
AnyType): The type of the elements to allocate storage for.
Args:
Returns:
Pointer[type, MutUntrackedOrigin]: A pointer to the newly allocated uninitialized array.
def alloc[T: AnyType, /](layout: Layout[T], /) -> Allocation[T]
Allocates owned storage for layout.count() 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](count=4))
var ptr = allocation.unsafe_ptr()
for i in range(4):
ptr.unsafe_offset(i).unsafe_write(i)
dealloc(allocation^)
Constraints:
size_of[T]() must be greater than zero. layout.count() must be
greater than zero.
Parameters:
- T (
AnyType): The type of the elements to allocate storage for.
Args:
- layout (
Layout[T]): Describes the number of elements and alignment of the allocation.
Returns:
Allocation[T]: An Allocation owning the newly allocated, uninitialized storage.