Skip to content

1. The unsafe boundary

Safe Flecha proves checked-reference lifetimes, slice bounds, resource moves, and typed calls. unsafe exists for raw addresses, raw allocation, and native contracts whose validity comes from outside those proofs. Before using it, write the invariant in plain language and check whether a checked reference, checked slice, owned value, or standard-library wrapper already expresses it.

Put the raw operation in a private function or tiny block. Validate sizes, alignment, nullability, lifetime, ownership, and error behavior before crossing the boundary. Return an ordinary safe value or explicit error; do not make every caller repeat the proof.

Tested example

Write the pointer contract at the smallest boundary while ordinary address copying stays safe.

File: curriculum/main-evidence/single/unsafe_pointers.fl

curriculum/main-evidence/single/unsafe_pointers.fl
// Build: build/flecha build examples/unsafe_pointers.fl -o build/unsafe_pointers
// Prints 42 and exits with 42. All pointers below refer to live local storage.
unsafe void write(constptr i32 destination, i32 value) {
// The pointer binding is fixed; its target remains writable.
*destination = value;
}
unsafe i32 read(*const i32 source) {
// The target is read-only, including inside this unsafe function.
return *source;
}
*i32 pass_pointer(*i32 pointer) {
// Copying an address does not access its target and needs no unsafe block.
return pointer;
}
i32 main() {
i32 value = 0;
*i32 pointer = none;
if pointer != null { return 1; }
unsafe {
pointer = &raw value;
write(pointer, 40);
constptr i32 fixed = pointer;
*fixed = *fixed + 2;
// Read-only access may be added, but never removed implicitly.
*const i32 readOnly = fixed;
if read(readOnly) != 42 { return 2; }
// Nested pointers preserve each layer's qualifiers.
**i32 slot = &raw pointer;
if **slot != 42 { return 3; }
}
pointer = pass_pointer(pointer);
unsafe {
// value still lives here. The unsafe block did not free anything.
if *pointer != 42 { return 4; }
}
stdoutln(value);
return value;
}

The block above is the complete file executed by the commands below.

The safe binding keeps ordinary address copying outside unsafe. Only the operation that dereferences the raw pointer crosses the boundary, which limits the invariant a reviewer must establish.

Commands

Commands
flecha check curriculum/main-evidence/single/unsafe_pointers.fl
flecha build curriculum/main-evidence/single/unsafe_pointers.fl -o build/unsafe_pointers
build/unsafe_pointers

Expected output

Expected output
42
exit status: 42

Related reference: /examples/unsafe_pointers/.