Manual Memory and unsafe

Raw pointers, the unsafe block, and the ownership rules the checker enforces.

vlatest

Everything on this page is gated behind an unsafe block. Outside one, the compiler rejects raw pointer work with E0520 unsafe required.

Taking an address

&x takes the address of a variable and produces a raw pointer of type *T. *p dereferences, and p.field auto-dereferences for you. Raw pointers do not own what they point at, and the collector does not track them.

A pointer binding needs its *T type written out. There is no inference for raw pointers:

class Box {
    var n: int

    constructor(n: int) {
        this.n = n
    }
}

fn main() {
    let a = Box(1)

    unsafe {
        let p: *Box = &a
        p.n = 42
        println(p.n)         // 42
        println((*p).n)      // 42
    }

    println(a.n)             // 42 - the pointer wrote through
}

unsafe is an expression, so it can also wrap a single value. Because it is a normal block, ordinary statements inside it behave as usual.

What the block unlocks

Inside unsafe { } the checker additionally allows:

  • raw pointer types, & and *;
  • pointer dereference and pointer member access;
  • indexing and stores through a raw pointer;
  • the raw-buffer builtins alloc and free.

The block is a promise, not a check. The compiler does not verify that a pointer is still live, that it points at the right type, or that you free it.

#[manualAlloc] and owned values

An instance field can be marked #[manualAlloc] to say the field owns a value that must be released. The checker is strict about where such a value may go, and every rule has its own code:

Rule Code
free is only available on a #[manualAlloc] binding E0503
A #[manualAlloc] value cannot be stored, assigned or bound E0504
A #[manualAlloc] binding cannot be overwritten, and cannot be returned E0505
The attribute takes no arguments, and is rejected on static fields and constants E0401
The marked field must be a class or struct type E0401
Using a value after free() or after a move E0501
Freeing the same value twice E0502

An owned field is freed recursively when the object that owns it is freed.

Raw buffers

alloc and free manage a raw buffer. alloc takes a scalar element type (int, float, bool or char) and a count, and free takes the pointer it returned. Both are gated behind unsafe:

unsafe {
    let p = alloc(int, 16)
    let first = *p
    free(p)
}

free is checked at compile time: handing it anything other than the pointer alloc returned is E0440.

A &T is an immutable reference. It reads through a pointer and does not write, so *p = 7 on a &T is rejected with E0362. To write, bind a raw pointer *T and assign through it, the way p.n = 42 does in the Box example above.

Assigning to a variable, a field or an index you already own needs no unsafe block at all.