// Allocation and deallocation#i32 numbers = alloc(100); // allocate array of 100 i32s#f64 zeros = alloc(50, 0.0); // allocate and initializefree(numbers); // deallocate// Reallocation (expand or relocate existing allocation)numbers = realloc(numbers, 200); // expand or move allocationif (numbers == null) { // realloc failed, original memory still valid}// Memory copyingcopy(destination, source, count); // built-in memory copy
Automatic Resource Management
Defer Statements
// Defer statements (execute at function return)void = process_file(str filename) { #u8 buffer = alloc(1024); defer free(buffer); // executed when function returns if (some_condition) { return; // defer executes here } // defer also executes at normal function end}// Defer with blocksvoid = complex_processing() { defer { cleanup_temp_files(); reset_global_state(); }; // multiple operations deferred together}
Context Managers
Defining Context Managers
// Define context manager for file handlingfile = context enter(str path, str mode) { // open file and return handle}void = context exit(file f) { // close file automatically}
Using Context Managers
// Usage with automatic cleanupvoid = read_config() { with f = file("config.txt", "r") { data = read_all(f); process_config(data); // file automatically closed on exit } catch (err) { case (FileNotFound) { printf("Config file not found\n"); } }}
// Borrowing for read-only accessf64 = calculate_determinant(#Matrix m) { // can read m, cannot modify // caller retains ownership}// Mutable borrowing for in-place operationsvoid = transpose_inplace(~Matrix m) { // exclusive access to modify m // caller retains ownership after function returns}
Usage Example
Matrix mat := create_identity(3); // takes ownershipf64 det = calculate_determinant(#mat); // lends for readingtranspose_inplace(~mat); // lends for modification// mat still owned and valid here
Memory Safety Rules
Ownership Transfer: Use := to transfer ownership
Borrowing: Use #= for immutable borrows, ~= for mutable borrows
No Use After Move: Cannot access moved values
Exclusive Mutable Access: Only one mutable borrow at a time