Heap allocation routines; alloc and New

The following are the heap allocation routines found inside the Jai Basic module. By default, they function basically the same as in C or C++; when you allocate, you also need to free. alloc in Jai is the same as malloc in C. alloc returns a pointer to uninitialized memory. New in Jai is the same as new in C++.

#import "Basic";

a := alloc(size_of(int));  // heap allocates 8 bytes, alloc returns *void
b := New(int);             // heap allocates an int
c := NewArray(10, int);    // heap allocates an [] int array of size 10

You can cache align a heap allocation by passing an alignment parameter to New. For example, if you need your heap allocation to be 64-bit cache aligned, you can do:

array := NewArray(500, int, alignment=64);

to make the array 64-bit cache aligned.

These are the corresponding memory freeing routines associated with allocation.

#import "Basic";

free(a);       // frees allocated int variable "a"
free(b);       // frees allocated int variable "b"
array_free(c); // frees allocated array "c"
1 Like