Skip to content

Pointers & Memory

Chuks provides a hybrid memory model that combines the safety of garbage-collected languages (like Java/Python) with the control of pointers found in systems languages (like C/Go).

By default, all primitive types in Chuks are passed by value. This means when you pass a variable to a function, the function receives a copy.

function modify(val: int): void {
val = 100; // This only changes the local copy
}
var x = 10;
modify(x);
println(x); // Still 10

Objects are reference types. When you pass an object, you are passing a reference to the same underlying data.

class User {
public age: int;
}
function birthday(u: User): void {
u.age = u.age + 1; // This modifies the original object
}
const user = new User();
user.age = 20;
birthday(user);
println(user.age); // 21

Sometimes you want to modify a primitive value (like an int or string) inside another function without wrapping it in a class. You can do this using pointers.

  • &variable (Address-of): Gets the memory address of a variable.
  • *pointer (Dereference): Accesses or modifies the value at that address.
  • *Type: Type annotation for a pointer (e.g., *int, *string).
// Function accepts a pointer to an integer (*int)
function increment(ptr: *int): void {
*ptr = *ptr + 1; // Update the value at the address
}
var count = 0;
increment(&count); // Pass the address of 'count'
println(count); // Output: 1
Use CaseRecommended?Why?
Modifying Primitives✅ YesTo change an int, bool, or string in a helper function.
Performance⚠️ MaybeAvoiding copies of large structs (future feature). Currently, objects are references anyway.
Optional Values❌ NoUse null or Option<T> (future) instead of pointers for nullability.

Chuks safeguards memory to prevent common crashes seen in C/C++.

Pointers in Chuks track Stack Indices, not raw memory addresses. If the underlying VM stack grows or moves, your pointers remain valid.

You should not return a pointer to a local variable from a function.

// ❌ BAD: Returning pointer to local stack variable
function getPointer(): *int {
var local = 42;
return &local; // Unsafe! 'local' is destroyed when function returns
}

The compiler will allow this (for now), but dereferencing such a pointer later could lead to unpredictable results or data corruption as the stack frame is reused.

You cannot do ptr + 1 to access the next memory slot. Chuks pointers are transparent references, not tools for manual memory traversal.

  1. Primitives (int, bool) are passed by value (copied).
  2. Objects (class, [], {}) are passed by reference (shared).
  3. Use Pointers (*int) only when you need to modify a primitive value inside another function.