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.
What happened to UnsafePointer?
Section titled “What happened to UnsafePointer?”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:
5It 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.
Allocating memory
Section titled “Allocating memory”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 30Step by step:
alloc(Layout[Int](count=4))reserves room for 4Intvalues on the heap. (alloc[Int]({count = 4})is a shorter way to write the same thing.)allocation.unsafe_ptr()gives you aPointerto the first slot.ptr.unsafe_offset(i)is a pointer to slot numberi.unsafe_write(value)puts a value into that slot.ptr[unsafe_offset=i]reads sloti.dealloc(allocation^)gives the memory back. The^is there becausedeallocconsumes the allocation.
Forgetting to free is a compile error
Section titled “Forgetting to free is a compile error”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 managerAnd 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.
A span over the memory
Section titled “A span over the memory”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.
Cleaning up values before freeing
Section titled “Cleaning up values before freeing”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! worldall cleaned upunsafe_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.
Wrapping it in a struct
Section titled “Wrapping it in a struct”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 intscopied 3 ints into new memoryfreed 3 intsa[0] = 7freed 3 intsb[0] = 99The 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.
What can go wrong
Section titled “What can go wrong”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 memorydealloc(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 freedAnd 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
deallocon memory that still holdsStrings 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.
Practice
Section titled “Practice”1. Squares in raw memory
Section titled “1. Squares in raw memory”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 16Every slot is written before it’s read, and the allocation is freed once at the end.
2. Find the bug
Section titled “2. Find the bug”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 textThe output looks the same either way, which is exactly why leaks are easy to miss.
- In Mojo 1.2,
UnsafePointeris a deprecated alias forPointer; unsafe work usesPointer’sunsafe_methods. alloc(Layout[T](count=n))returns anAllocation; you must free it withdealloc(allocation^), or the program won’t compile.- New memory is uninitialized: put the first value in a slot with
unsafe_write, never withptr[] = .... deallocdoesn’t run destructors: callunsafe_deinit_pointee()(orunsafe_destroy_n) first for types likeString.- 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
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Using pointers: the manual’s guide to allocating, initializing, reading and freeing memory with
Pointer. - alloc module:
alloc,dealloc,Layout,Allocation,ThinAllocationandinto_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.