.\" Made by website/plain/build.mjs from website/words/unsafe.md; change that file. .TH SG-UNSAFE 7 2026-11-28 "SG" "SG reference" .SH NAME unsafe \- marks code the checker cannot follow: raw memory, calls of C, the fields of a union .SH SYNOPSIS .TP \fBunsafe { ... }\fR a block of statements that reach what the checker cannot follow .TP \fBunsafe value\fR the same for one expression: unsafe p[0], unsafe abs(-7) .TP \fBstruct T : unsafe Sendable\fR the writer's promise that a struct holding raw pointers may go to another task .TP \fBrequire name address version unsafe\fR a line of sg.project that allows a package with unsafe or extern in it .SH DESCRIPTION The checker follows every value: who owns it, who borrows it, how long it lives. A few things are out of its sight: memory reached through a \fBraw T\fR, a function of C, the bits of a union read as another type. Those are written inside \fBunsafe\fR, which says that here the writer, not the compiler, keeps memory safe. Outside \fBunsafe\fR there is no use after free, no read out of bounds and no data race, so when memory does go wrong the cause is in an \fBunsafe\fR place or in C. .PP The word is asked for by what touches memory, not by where a pointer came from. Making room with \fBMemory.allocate\fR, keeping and copying a pointer, comparing two (\fBp == null\fR, \fBp < q\fR) and counting the items between them (\fBq \- p\fR) need no \fBunsafe\fR\&. These need it, and nothing else does: .PP - an item of raw memory, read or written: \fBp[i]\fR, \fBp[i].x\fR; .PP - moving a pointer: \fBp + n\fR; .PP - a cast between raw pointers, from a number to a raw pointer, from a \fBraw void\fR to a \fBCFunc\fR, and \fB(ref T)p\fR or \fB(read T)p\fR, which lend the value at an address \fBMemory.addressOf\fR gave; .PP - reading a field of a union; .PP - \fBMemory.free\fR, \fBMemory.copy\fR, \fBMemory.view\fR, \fBMemory.viewRef\fR, \fBMemory.addressOf\fR, \fBMemory.readVolatile\fR, \fBMemory.writeVolatile\fR, \fBMemory.readUnaligned\fR and \fBMemory.writeUnaligned\fR; .PP - \fBFile.mapRead\fR, the bytes of a file where the system keeps them; .PP - a call of a function of C, a call through a \fBCFunc\fR, and a variable of C; .PP - \fBstring.fromCString\fR\&. .PP An \fBunsafe\fR that nothing needs is an error, so the word always marks a real place. .PP There is no \fBunsafe\fR function. A function that needs \fBunsafe\fR writes it inside, and its callers write none. That is how unsafe code is kept small: a struct or a module holds the raw memory or the calls of C in a few lines, checks what it is given in front of them, and gives the rest of the program safe types. .PP The interpreter checks each item of raw memory against its block, and stops the program at an item outside it, after \fBMemory.free\fR and through \fBnull\fR\&. A pointer made from a number, or read out of a union, is checked as the pointer that was made into that number was, or against the block it lies in; one that no pointer was made into and that lies in no block reaches nothing, and neither does the address \fBMemory.addressOf\fR gives, which in the interpreter names a value without being where its bytes lie. Memory C gave is not checked. Compiled code checks none of this: a \fBraw T\fR is a pointer of C and costs what C costs. So unsafe code is tried in the interpreter first. .PP A raw pointer does not go to another task, since the checker cannot tell whether two tasks would reach what it points at. A package with \fBunsafe\fR or \fBextern\fR in its source is built only when the program allows it, with \fBunsafe\fR at the end of the package's line: \fBrequire zlib example.com/bo/zlib 1.2.0 unsafe\fR\&. .SH EXAMPLES .SS "Raw memory" .RS 4 .nf void main() { var scores = Memory.allocate(3) unsafe { scores[0] = 90 scores[1] = 75 scores[2] = scores[0] - 5 } var last = unsafe scores[2] print(last) unsafe Memory.free(scores) } .fi .RE .PP .RS 4 .nf 85 .fi .RE .PP \fBMemory.allocate\fR gives room for three \fBint\fRs, all zero, and needs no \fBunsafe\fR\&. Each item read or written does: the checker does not know how many items the block holds, or whether it is still there. .SS "A function of C" .RS 4 .nf extern { nuint strlen(read CString text) int abs(int value) } void main() { var name = CString.from("Pasha") ?? panic("a zero byte inside") print(unsafe strlen(read name)) unsafe { var distance = abs(3 - 10) print(distance) } } .fi .RE .PP .RS 4 .nf 5 7 .fi .RE .PP \fBextern { }\fR declares functions of the C library. The checker cannot see what they do, so every call is inside \fBunsafe\fR; a block covers several statements. .SS "A pointer that moves" .RS 4 .nf void main() { var readings = Memory.allocate(4) for i in 0..4 { unsafe { readings[i] = (long)(i + 1) * 10 } } var end = unsafe (readings + 4) var at = readings long total = 0 while at < end { total += unsafe at[0] at = unsafe (at + 1) } print($"{total} from {end - readings} items") print(at == end) unsafe Memory.free(readings) } .fi .RE .PP .RS 4 .nf 100 from 4 items true .fi .RE .PP \fBp + n\fR moves by items and needs \fBunsafe\fR\&. Comparing two pointers and \fBend \- readings\fR, the count of items between them, read no memory and need none. .SS "The bits of a float" .RS 4 .nf union Bits { uint word float number } void main() { var bits = Bits { number = 1.0 } print($"{unsafe bits.word:x8}") } .fi .RE .PP .RS 4 .nf 3f800000 .fi .RE .PP A union holds one of its fields in the same bytes. Writing a field is safe; reading one is inside \fBunsafe\fR, since it reads the bytes as its own type, whichever field was written last. .SS "Unsafe kept inside a struct" .RS 4 .nf struct Stack : Disposable { raw int items nint capacity nint count Stack create(nint capacity) { return Stack { items = Memory.allocate(capacity), capacity = capacity, count = 0 } } void push(ref this, int value) { if this.count == this.capacity { panic("the stack is full") } unsafe { this.items[this.count] = value } this.count += 1 } int pop(ref this) { if this.count == 0 { panic("the stack is empty") } this.count -= 1 return unsafe this.items[this.count] } void dispose(ref this) { unsafe Memory.free(this.items) } } void main() { var stack = Stack(2) stack.push(1) stack.push(2) print(stack.pop()) stack.push(3) print(stack.pop()) print(stack.pop()) } .fi .RE .PP .RS 4 .nf 2 3 1 .fi .RE .PP The check in front of each \fBunsafe\fR line keeps every index inside the block, and \fBdispose\fR frees it once, when the stack's owner ends. \fBmain\fR writes no \fBunsafe\fR at all. .SS "A raw pointer for another task" .RS 4 .nf struct Buffer : unsafe Sendable { raw long items nint count } long sum(Buffer buffer) { long total = 0 for item in unsafe Memory.view(buffer.items, buffer.count) { total += item } return total } void main() { var items = Memory.allocate(100) for i in 0..100 { unsafe { items[i] = (long)i } } var task = Task.run(sum, Buffer { items = items, count = 100 }) print(task.wait()) unsafe Memory.free(items) } .fi .RE .PP .RS 4 .nf 4950 .fi .RE .PP \fB: unsafe Sendable\fR is the writer's promise that no two tasks change what the pointer reaches at once: here only the task reads it, and \fBmain\fR frees it after \fBwait\fR\&. \fBMemory.view\fR lends the items as a \fBread long[]\fR, which \fBfor\fR walks with its usual checks. .SH "WHAT STOPS THE PROGRAM" .SS "Raw memory read after it is freed" .RS 4 .nf void main() { var scores = Memory.allocate(3) unsafe Memory.free(scores) var first = unsafe scores[0] print(first) } .fi .RE .PP .RS 4 .nf panic: raw memory is read after it was given back with `Memory.free` --> example.sg:4:17 4 | var first = unsafe scores[0] | ^^^^^^^^^^^^^^^^ .fi .RE .PP The checker takes this program; the interpreter stops it as it runs. A compiled build checks nothing: it reads whatever the freed memory holds, as a program of C would. .SH "WHAT THE COMPILER REFUSES" .SS "Raw memory without unsafe" .RS 4 .nf void main() { var scores = Memory.allocate(3) scores[0] = 90 unsafe Memory.free(scores) } .fi .RE .PP .RS 4 .nf error: this reaches raw memory, whose size and life the checker does not know, so it is written inside `unsafe` --> example.sg:3:5 3 | scores[0] = 90 | ^^^^^^^^^ hint: a write is a statement: `unsafe { scores[0] = ... }` .fi .RE .SS "A call of C without unsafe" .RS 4 .nf extern { int abs(int value) } void main() { print(abs(-12)) } .fi .RE .PP .RS 4 .nf error: `abs` is a function of C, and the checker cannot see what it does, so it is written inside `unsafe` --> example.sg:6:11 6 | print(abs(-12)) | ^^^^^^^^ hint: `unsafe abs(-12)`, or `unsafe { ... }` around several statements .fi .RE .SS "An unsafe that nothing needs" .RS 4 .nf void main() { var scores = Memory.allocate(3) var empty = unsafe (scores == null) print(empty) unsafe Memory.free(scores) } .fi .RE .PP .RS 4 .nf error: nothing here needs `unsafe` `unsafe` is for what the checker cannot follow, such as an item of raw memory (`p[i]`), a field of a union read, `Memory.free` or a call of a C function; `sg help unsafe` lists every case --> example.sg:3:17 3 | var empty = unsafe (scores == null) | ^^^^^^ hint: leave `unsafe` out .fi .RE .PP Comparing a pointer with \fBnull\fR reads no memory. .SS "A raw pointer sent to a task without the promise" .RS 4 .nf struct Buffer { raw long items nint count } long sum(Buffer buffer) { long total = 0 for item in unsafe Memory.view(buffer.items, buffer.count) { total += item } return total } void main() { var items = Memory.allocate(100) var task = Task.run(sum, Buffer { items = items, count = 100 }) print(task.wait()) unsafe Memory.free(items) } .fi .RE .PP .RS 4 .nf error: `sum` takes a `Buffer` here, which holds a `raw long` (the field `items` of `Buffer`), which cannot go to another task: the checker does not follow a raw pointer, and two tasks could reach what it points at at once; a struct that keeps what it reaches safe for several tasks says so with `: unsafe Sendable` .fi .RE .SH "SEE ALSO" .BR sg-raw (7), .BR sg-extern (7), .BR sg-export (7), .BR sg-union (7) .PP https://sg\-lang.org/reference/unsafe.html