Version: 1.1.0

Intro to pointers

Pointers name memory. Mojo's safe collections should be your first choice. Pointers are for layouts, interop, and kernels that need an address.

Essentials

  • UnsafePointer[T] is an address of one or many T values.
  • Span[T] is a pointer plus a length.
  • Allocating memory does not initialize it.
  • You free what you allocate, unless a collection owns the pointer.
  • Dangling and out-of-bounds access are undefined. The type is named unsafe for that reason.

Example

fn main():
    var ptr = alloc[Int](4)
    ptr[0] = 7
    print(ptr[0])
    ptr.free()

Keep in mind

Wrap a pointer inside a struct with a destructor when the allocation has a single owner.