Lyricdev
GitHub

LYR-SEM0233

a memory operation outside an unsafe block

error · spec 13-abi

A pointer's read, write, offset or cast, std.ffi's alloc or free, or GcHandle.from, is called outside an unsafe { … } block.

Explanation

These operations hold to what the compiler cannot see: that memory is there, that it holds a value of the type, that nothing else frees it. The unsafe block is where the program says it holds to that, and the one place a reader looks for it. Calling a C function is not unsafe, and neither is an array's asPtr(); what reads and writes through the pointer is.

Put the call in an unsafe { … } block, as small as it can be.

Wrong

import std.ffi { alloc, free };

fn main(): void {
    let p = alloc<int>(1);
    p.write(7);
    free(p);
}
import std.ffi { alloc, free };

fn main(): void {
    unsafe {
        let p = alloc<int>(1);
        p.write(7);
        free(p);
    }
}