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.
Safety:
- The returned memory is uninitialized; reading before writing is undefined.
- The returned pointer has an empty mutable origin; you must call
free()to release it.
Example:
var ptr = alloc[Int32](4)
ptr.store(0, Int32(42))
ptr.store(1, Int32(7))
ptr.store(2, Int32(9))
var a = ptr.load(0)
print(a[0], ptr.load(1)[0], ptr.load(2)[0])
ptr.unsafe_free()
Constraints:
count must be positive and size_of[type]() must be > 0.
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.