9. @NoAlloc
@NoAlloc on a function (or a property getter or setter) says that its body must not allocate.
kotlin
@file:MemoryMode(Mode.Strict)
import mini.memory.*
class Vec(val x: Int, val y: Int)
@NoAlloc
fun dist2(a: Int, b: Int): Int {
val v = Vec(a, b) // does not escape: lives on the stack, allowed
return v.x * v.x + v.y * v.y
}
fun main() {
println(dist2(1, 2))
}This is a Strict file, but it needs no allocator: Vec does not escape. The program builds and runs natively in CI:
text
5An allocation that escapes, or a call of alloc.allocate(...), is an error:
kotlin
@file:MemoryMode(Mode.Strict)
import mini.memory.*
class Box(val v: Int)
@NoAlloc
context(h: Heap)
fun make(): @Owned Box = Box(1) // the Box escapes, so it is a real allocation
fun main() {
context(Heap()) { make().free() }
}Limits
- Only the body of the annotated function is checked. Calls to other functions are not followed yet (that needs function summaries and is planned).
- Only allocations that actually are not on the stack count; non-escaping objects are fine.
- A warning for allocations in hot paths outside
@NoAllocis planned.
This is the last page of the guide. Look up any code in the diagnostics reference, or read how the checker works in Memory checker.