Skip to content
Systems programming for what’s next.
— Vex

Unsafe Code ​

unsafe marks a boundary where the caller must establish memory or foreign-API preconditions that the compiler cannot prove. It does not disable type checking or make an invalid operation valid.

WARNING

Unsafe code can cause memory corruption, undefined behavior, and security vulnerabilities. Always wrap unsafe code in safe abstractions.

Unsafe Blocks ​

The unsafe { } block allows operations that the compiler cannot verify as safe:

vex
fn main() {
    let value: i64 = 42
    let ptr = &value as Ptr<i64>
    
    // Unsafe block for raw pointer dereference
    let read_val = unsafe { ptr.read() }
    
    $println(f"Value: {read_val}")
}

What Requires Unsafe? ​

OperationWhy Unsafe?
Raw pointer read/writePointer may be null or dangling
Calling unsafe fnFunction has manual safety requirements
Foreign calls (LIBC/SYSTEM/NATIVE)No safety guarantees for foreign code
Mutable global accessRisk of data races

Unsafe Functions ​

Declare functions with the unsafe keyword to signal manual safety requirements:

vex
// Caller must supply a live, aligned pointer to an initialized i64,
// readable for this call and compatible with all outstanding aliases.
unsafe fn rawRead(ptr: Ptr<i64>): i64 {
    return ptr.read()
}

fn main() {
    let val = 100
    let ptr = &val as Ptr<i64>
    
    // Must call within unsafe block
    let result = unsafe { rawRead(ptr) }
}

Raw Pointers ​

Vex distinguishes between references (&T) and canonical raw pointers (Ptr<T> and Ptr<T!>).

Creating Raw Pointers ​

vex
let x = 42
let ptr = &x as Ptr<i32>       // Readable raw pointer
let! y = 100
let ptrMut = &y! as Ptr<i32!>   // Writable-pointee capability

Dereferencing ​

Dereferencing a raw pointer is always unsafe:

vex
let x = 42
let ptr = &x as Ptr<i32>
let val = unsafe { ptr.read() }

let! y = 100
let ptrMut = &y! as Ptr<i32!>
unsafe { ptrMut.write(200) }

Mutable Global Variables ​

Accessing mutable global variables requires unsafe due to potential data races:

vex
let! COUNTER: i32 = 0

fn increment() {
    unsafe {
        COUNTER += 1
    }
}

fn get_count(): i32 {
    return unsafe { COUNTER }
}

Best Practices ​

  1. Minimize Unsafe Scope: Keep unsafe blocks as small as possible.
  2. Safe Wrappers: Always prefer wrapping unsafe modules in a clean, safe Vex API.
  3. Prove the full memory contract: Null and bounds checks are necessary in many APIs, but do not prove alignment, initialization, lifetime or aliasing validity.
  4. Pair ownership and cleanup: Release each allocation through its owning allocator, and do not use pointers or views after release.
  5. Document the caller obligation: A public unsafe fn must state what storage is valid, for how long, and whether another thread may access it.

Next Steps ​

Released under the MIT License.