typestar

Unsafe pointers in Mojo

alloc hands back raw memory that you index directly and must free yourself.

from std.memory import alloc, memset_zero


def main():
    var block = alloc[Int32](4)
    memset_zero(block, 4)
    print(block[0], block[3])
    for i in range(4):
        block[i] = Int32(i * i)
    print(block.load(2))
    block.store(3, Int32(100))
    print(block[3])
    block.free()

How it works

  1. alloc[Int32](4) reserves four slots and returns an UnsafePointer.
  2. memset_zero clears them; indexing, load, and store read and write.
  3. block.free() releases the block - nothing else will.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
251
Tokens
82
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 76 seconds.

Type this snippet

Step 1 of 4 in Memory, step 17 of 22 in Parameters & SIMD.

← Previous Next →