18. Pointers and allow unsafe
*T is the address of a T, or null. Pointer types can be written,
stored, passed, returned and compared with == anywhere, and a.create(v)
makes one; null takes its pointer type from context (E115 otherwise).
Using a pointer needs the line
allow unsafe
in the file (anything else after allow is E131). Then:
| Written | Means |
|---|---|
&place |
the address of a var or an inout parameter, or of its field or element (a const is E105), where a pointer is expected: const p: *T = &x, a *T argument (without the type, const r = &x is a borrow, section 12) |
p.* |
the T that p points to; also a place: p.* = v, p.*.x = v |
@ptrAdd, @ptrCast, @intFromPtr, @ptrFromInt, @strPtr, @bufPtr, @sliceFromPtr |
section 15 |
extern fn |
section 20 |
Without allow unsafe these are E131 (and &x outside an inout argument
stays E121; a borrow is allowed everywhere). The compiler cannot check what pointers point to: a pointer
can outlive the variable it points into, and @ptrAdd can leave the
object. The one check is that p.* on null panics with
null pointer dereference. Nor can it see a pointer into a value passed
as inout: while the call runs, the inout parameter must be the only way
to that value, so reading or writing it through a pointer taken earlier
is undefined.
allow unsafe is local to its file: a file that imports an unsafe module
does not need it, so an unsafe module can offer a safe API. Unlike a
capability, it does not travel along the call graph. The language server
marks functions of an unsafe file in hover.
// expect: 6
// expect: 42
uses io, alloc
allow unsafe
const Node = struct {
value: i64
next: *Node
}
fn sum(list: *Node) i64 {
var total = 0
var p = list
while (p != null) {
total = total + p.*.value
p = p.*.next
}
return total
}
fn bump(p: *i64) void {
p.* = p.* + 1
}
fn main(io: Io, a: Allocator) void {
var list: *Node = null
list = a.create(Node{ .value = 1, .next = list })
list = a.create(Node{ .value = 5, .next = list })
io.print(sum(list))
var x = 41
bump(&x)
io.print(x)
}
// error: E131
uses io, alloc
fn main(io: Io, a: Allocator) void {
const p = a.create(5) // fine: making a pointer is safe
io.print(p.*) // reading through it is not
}