Unsafe
Also known as: unsafe pointer raw pointer malloc free calloc ffi c memory
● Advanced5 minBefore this: Automatic MemorySpec 6.4
unsafe { … } turns off the safety checks for a block, to work with raw memory and C. A package must allow it.
[package]
name = "pointers"
version = "0.1.0"
unsafe = truefn main() {
unsafe {
const p: Ptr<Int32> = alloc(3)
*p = 7
p[1] = 8
const q = p + 2
*q = *p + p[1]
print(p[2])
free(p)
}
}15
- A
Ptr<Int32>is a C pointer.allocandfreeare C's, so C can free what Kavach allocated. - C's syntax works inside
unsafe:*p,p[1],p + 2. - A package uses
unsafeonly withunsafe = truein itskavach.toml, andkavach auditlists every place.
Every operation
| Operation | Does |
|---|---|
alloc(n) | n values of T, set to zero, from C's calloc; the type comes from where the result goes (const p: Ptr<Int32> = alloc(4)) |
free(p) | Gives the memory back (C's free), so C code may free what Kavach allocated and the other way round |
p.read(i) | The ith value (from 0) |
p.write(i, v) | Sets the ith value to v |
p.text() | For a Ptr<UInt8>: a copy of the text there, up to the first zero byte, as C keeps text; none for a null pointer; bytes that aren't UTF-8 panic |
p.bytes(n) | For a Ptr<UInt8>: a copy of the n bytes there, as Bytes; .text() on them gives none for bytes that aren't UTF-8, where p.text() panics |
Ptr.from_int(n) | The address n, for values C defines as numbers cast to pointers (SQLite's SQLITE_TRANSIENT is -1) |
Nothing is checked inside unsafe: an index past the end or a pointer used after free is as dangerous as in C. Keep it in one small function with a safe signature. Pointers run in native code.