Skip to content

Mojo Unsafe Pointers

Everything so far has been safe: the compiler made sure no value was used after it was gone. Sometimes you need to step outside that and manage a block of memory yourself, for example to build your own collection like List, or to share a buffer with C code. Mojo lets you do that with a set of operations whose names all start with unsafe_. “Unsafe” here means: you are now responsible for using the memory correctly, and if you get it wrong, your program can crash or quietly corrupt data. This page shows how it works with small, correct examples, and is honest about the risks.

Older Mojo code and tutorials use a type called UnsafePointer. In Mojo 1.2, Pointer and UnsafePointer have been merged into one type: Pointer. The old name still exists as an alias, but it’s deprecated:

from std.memory import UnsafePointer
def main():
var n = 5
var p = UnsafePointer(to=n)
print(p[])

Output:

5

It runs, but the compiler warns: 'UnsafePointer' is deprecated, use 'Pointer' instead. So the “unsafe pointer” of Mojo 1.2 is just a Pointer used with its unsafe_ methods. The standard library note on UnsafePointer says the same. Everything below uses Pointer.

To get your own block of memory, call alloc with a layout: the type of value and how many of them. It gives you back an Allocation, a handle that owns the memory:

from std.memory import alloc, dealloc, Layout
def main():
var allocation = alloc(Layout[Int](count=4))
var ptr = allocation.unsafe_ptr()
for i in range(4):
ptr.unsafe_offset(i).unsafe_write(i * 10)
for i in range(4):
print(ptr[unsafe_offset=i], end=" ")
print()
dealloc(allocation^)

Output:

0 10 20 30

Step by step:

  • alloc(Layout[Int](count=4)) reserves room for 4 Int values on the heap. (alloc[Int]({count = 4}) is a shorter way to write the same thing.)
  • allocation.unsafe_ptr() gives you a Pointer to the first slot.
  • ptr.unsafe_offset(i) is a pointer to slot number i. unsafe_write(value) puts a value into that slot.
  • ptr[unsafe_offset=i] reads slot i.
  • dealloc(allocation^) gives the memory back. The ^ is there because dealloc consumes the allocation.

An Allocation must be freed. It’s an explicitly destroyed type (like the tickets in Mojo Destructors), so if you forget dealloc, the program doesn’t build:

from std.memory import alloc, dealloc, Layout
def main():
var allocation = alloc(Layout[Int](count=4))
var ptr = allocation.unsafe_ptr()
ptr.unsafe_write(1)
print(ptr[])
hello.mojo:7:10: error: 'allocation' abandoned without being explicitly destroyed: An `Allocation` owns heap storage and must be consumed before it goes out of scope. Deallocate it with `dealloc(allocation^)`, or call `unsafe_leak()` to take ownership of the underlying pointer.
print(ptr[])
^
mojo: error: failed to run the pass manager

And because dealloc consumes the allocation, freeing it twice is caught too: the second dealloc(allocation^) is “use of uninitialized value ‘allocation’”. The pointer from unsafe_ptr() also keeps the allocation’s origin, so reading ptr[] after dealloc gives the same error. Mojo still catches the simplest mistakes, even here.

Writing one slot at a time is tedious. unsafe_span() gives you a Span over the whole block, with the usual indexing and printing:

from std.memory import alloc, dealloc, Layout
def main():
var allocation = alloc(Layout[Int](count=5))
var span = allocation.unsafe_span()
span.fill(0)
span[2] = 42
print(span)
dealloc(allocation^)

Output:

[0, 0, 42, 0, 0]

fill(0) writes a value into every slot, so after it, the memory is initialized and you can use it normally. It’s still called unsafe because nothing stops you from using the span before fill.

dealloc frees the memory, but it does not destroy the values stored in it. For an Int that doesn’t matter. For a String, which owns heap memory of its own, skipping its destructor would leak that memory. Destroy each value first:

from std.memory import alloc, dealloc, Layout
def main():
var allocation = alloc(Layout[String](count=2))
var ptr = allocation.unsafe_ptr()
ptr.unsafe_write("hello")
ptr.unsafe_offset(1).unsafe_write("world")
ptr[] += "!"
print(ptr[], ptr[unsafe_offset=1])
ptr.unsafe_deinit_pointee()
ptr.unsafe_offset(1).unsafe_deinit_pointee()
dealloc(allocation^)
print("all cleaned up")

Output:

hello! world
all cleaned up

unsafe_deinit_pointee() runs the destructor of the value a pointer points to, and leaves that slot uninitialized again. For many slots at once there’s unsafe_destroy_n(ptr, count) from std.memory.

There’s one more trap in this example. ptr[] += "!" is fine after unsafe_write. But ptr[] = "hello" on a fresh slot would be wrong: assigning through ptr[] first destroys the old value, and in fresh memory there is no old value, only garbage. Always use unsafe_write for the first value in a slot.

The way to use raw memory well is to hide it inside a struct. The struct allocates in __init__, frees in __deinit__, and never lets the raw pointer escape. Code that uses the struct is then safe again. This is how List works inside.

from std.memory import alloc, dealloc, Layout, Allocation
struct IntBuffer(Copyable):
var data: Allocation[Int]
var size: Int
def __init__(out self, size: Int):
self.size = size
self.data = alloc(Layout[Int](count=size))
self.data.unsafe_span().fill(0)
print("allocated", size, "ints")
def __init__(out self, *, copy: Self):
self.size = copy.size
self.data = alloc(Layout[Int](count=copy.size))
for i in range(copy.size):
self.data.unsafe_ptr().unsafe_offset(i).unsafe_write(copy[i])
print("copied", self.size, "ints into new memory")
def __getitem__(self, i: Int) -> Int:
return self.data.unsafe_ptr()[unsafe_offset=i]
def __setitem__(mut self, i: Int, value: Int):
self.data.unsafe_ptr()[unsafe_offset=i] = value
def __deinit__(deinit self):
dealloc(self.data^)
print("freed", self.size, "ints")
def main():
var a = IntBuffer(3)
a[0] = 7
var b = a.copy()
b[0] = 99
print("a[0] =", a[0])
print("b[0] =", b[0])

Output:

allocated 3 ints
copied 3 ints into new memory
freed 3 ints
a[0] = 7
freed 3 ints
b[0] = 99

The important part is the copy initializer (from Mojo Value Lifecycle). If it just copied the data field, both buffers would hold the same address, and both destructors would free the same memory: a double free. Instead, the copy allocates fresh memory and copies the numbers over, so a and b are fully separate, and each frees only its own block. (The “freed” lines appear between the prints because each buffer is destroyed right after its last use. Note that a[0] reads the value before a is freed.) __getitem__ and __setitem__ are what make a[0] work; see Mojo Special Methods.

Here’s the honest part. These mistakes compile without any error, and what they do at run time is undefined: the program might crash, print nonsense, or seem to work and break something else later. Don’t run them; just learn to recognize them.

Writing past the end of a block:

var allocation = alloc(Layout[Int](count=4))
var ptr = allocation.unsafe_ptr()
ptr[unsafe_offset=10] = 5 # slot 10 doesn't exist: corrupts other memory
dealloc(allocation^)

Using memory after freeing it, once the pointer has been taken out of the allocation with unsafe_leak(). That method gives you a pointer the compiler no longer tracks:

var ptr = alloc(Layout[Int](count=4)).unsafe_leak()
ptr.unsafe_write(1)
dealloc(ThinAllocation(unsafe_owned_ptr=ptr).unsafe_with_layout({count = 4}))
print(ptr[]) # the memory is already freed

And the other classics:

  • Reading uninitialized memory: reading a slot before writing it.
  • Leaking: taking a pointer with unsafe_leak() and never freeing it.
  • Skipping destructors: calling dealloc on memory that still holds Strings or lists.
  • Double free: two owners of the same block, like the copy initializer mistake above.

The manual’s page on using pointers lists the full set of unsafe operations and the rules for each. The short version: keep unsafe code small, keep it inside one struct, write it slowly, and test it well.

Allocate room for 5 Int values. Write the squares 0, 1, 4, 9, 16 into them, print them on one line, and free the memory.

Hint: write with ptr.unsafe_offset(i).unsafe_write(...), read with ptr[unsafe_offset=i], and finish with dealloc(allocation^).

Show solution
from std.memory import alloc, dealloc, Layout
def main():
var allocation = alloc(Layout[Int](count=5))
var ptr = allocation.unsafe_ptr()
for i in range(5):
ptr.unsafe_offset(i).unsafe_write(i * i)
for i in range(5):
print(ptr[unsafe_offset=i], end=" ")
print()
dealloc(allocation^)

Output:

0 1 4 9 16

Every slot is written before it’s read, and the allocation is freed once at the end.

This program compiles and runs, but it has a memory bug. What is it, and how do you fix it?

from std.memory import alloc, dealloc, Layout
def main():
var allocation = alloc(Layout[String](count=1))
var ptr = allocation.unsafe_ptr()
ptr.unsafe_write("a long piece of text")
print(ptr[])
dealloc(allocation^)

Hint: what does dealloc do, and what does it not do?

Show solution

dealloc frees the block but doesn’t run the String’s destructor, so the string’s own text memory is never freed: a leak. Destroy the value first:

from std.memory import alloc, dealloc, Layout
def main():
var allocation = alloc(Layout[String](count=1))
var ptr = allocation.unsafe_ptr()
ptr.unsafe_write("a long piece of text")
print(ptr[])
ptr.unsafe_deinit_pointee()
dealloc(allocation^)

Output:

a long piece of text

The output looks the same either way, which is exactly why leaks are easy to miss.

  • In Mojo 1.2, UnsafePointer is a deprecated alias for Pointer; unsafe work uses Pointer’s unsafe_ methods.
  • alloc(Layout[T](count=n)) returns an Allocation; you must free it with dealloc(allocation^), or the program won’t compile.
  • New memory is uninitialized: put the first value in a slot with unsafe_write, never with ptr[] = ....
  • dealloc doesn’t run destructors: call unsafe_deinit_pointee() (or unsafe_destroy_n) first for types like String.
  • Hide raw memory inside a struct that allocates in __init__, frees in __deinit__ and deep-copies in its copy initializer.
  • Out-of-bounds access, use after unsafe_leak() and uninitialized reads compile fine and fail at run time. Keep unsafe code small and careful.

Next up: errors, how Mojo functions report that something went wrong with raises and raise.

Quick check

1. What is UnsafePointer in Mojo 1.2?
2. You allocate memory with alloc and forget to call dealloc. What happens?
3. How should you put the first value into a freshly allocated slot?
4. A struct holds an Allocation and its copy initializer just copies the pointer. What goes wrong?

  • Using pointers: the manual’s guide to allocating, initializing, reading and freeing memory with Pointer.
  • alloc module: alloc, dealloc, Layout, Allocation, ThinAllocation and into_managed().
  • Pointer: every method, safe and unsafe_, on Mojo’s pointer type.
  • UnsafePointer: the note that it’s now a backward-compatible name for Pointer.