Forge

std.gc

Garbage-collected heap helpers (x86_64 only).

std.alloc’s alloc/free run over a 4 MiB GC heap with a conservative mark-and-sweep collector. std.gc exposes collection and statistics.

Functions

collect

def collect() -> void

Force a full mark-and-sweep collection. Roots are the live stack ([rbp, stack_top]) and .rodata.

from std.gc import collect

collect()

leak_check

def leak_check() -> uint64

Return the number of bytes currently allocated but unreachable from any live root (i.e. dropped without free). Useful for leak detection in tests.

from std.gc import leak_check

let leaked = leak_check()

Statistics

def alloc_count() -> uint64     # Total allocation calls
def free_count() -> uint64      # Total free calls
def collections() -> uint64     # Total collections performed
def heap_live() -> uint64       # Bytes currently live
def heap_capacity() -> uint64   # Total heap size (4 MiB)

Example: Leak Detection

from std.gc import collect, leak_check
from std.alloc import alloc
from std.io import puts
from std.fmt import format_i32
from std.alloc import free

pub def main() -> int32:
    let p = alloc(64)
    # p goes out of scope without free

    let buf: ptr[char] = alloc(16)
    collect()
    format_i32(buf, leak_check() as int32)   # 64
    puts(buf)
    return 0

Implementation

Conservative GC Details

Target Support

Target Available
x86_64 ✅ Full support
x86_32 ❌ Free-list allocator only — importing std.gc fails at codegen with a clean diagnostic
x86_16 ❌ (no heap)