-
Notifications
You must be signed in to change notification settings - Fork 4
Heap
Memory on the heap is allocated using the new
keyword. For example, new i32
allocates an i32 in heap and returns a pointer to the allocated memory.
var: *i32 = new i32;
new
keyword can be used with any type to allocate it on the heap. For example, variable lengths arrays can be created using the new
keyword like new [length]type
which returns a pointer to type
.
Memory can be initialized either by using the new
keyword to allocate memory and initializing it separately like ordinary pointers or by using the initialization syntax of the new
keyword. For example, new i32(100)
allocates an i32
on the heap, initializes it with value 100
, and returns a pointer to it.
Arrays, tuples, and structs can also be initialized with the same syntax like new [length]type {val1, val2, val3}
, new Struct {field1: prop1, field2: prop2}
and new Tuple {val1, val2}
Memory is freed using the delete
keyword. For example, delete ptr;
frees the memory ptr
points to. You can free multiple pointers in the same statement as delete ptr1, ptr2, ptr3;
. Freeing a pointer to stack memory or double freeing memory causes undefined behavior.
It's not necessary to manually free memory because Volant also has garbage collection.
You can also use the c-like malloc
, realloc
, calloc
and free
functions which are exported from heap.vo
.
import "heap.vo";
func main() i32 {
a: *u8 = heap.malloc(100);
heap.free(a);
}