Home/Documentation/Memory & Safety

Memory & Safety

Advanced: pointers, slices, checks, and contracts.

Advanced topic. Read this guide when you connect CK to another program or work directly with memory. The beginner lessons do not use pointers or slices.

CK functions can read memory provided by the program that calls them. Optional checks catch selected mistakes, but the calling program remains responsible for providing valid memory.

Pointers and slices#

ptr<T> is a raw typed pointer. slice<T> is a non-owning descriptor containing a typed data pointer and a u32 length. Build a slice with slice(data, len), index it with a u32, or take a half-open range with items[start..end].

export fn first(items: slice<i32>) -> i32 {
  return items[0];
}

The caller must ensure the allocation, extent, alignment, lifetime, and declared length are valid. Copying a slice does not copy its memory.

Checked execution modes#

Native and C support independent --overflow checked and --bounds checked options. Checked bounds cover slice index and sub-slice relations. They do not validate raw pointer indexing, arbitrary memory validity, or whether slice(data, len) describes a real allocation.

ckc build app.ck --kind executable --overflow checked --bounds checked --out app

Checked failures follow a documented status and first-error order. WebAssembly supports unchecked mode only. See the backend matrix before choosing a target.

Unsafe contracts#

An unsafe fn can state optimizer assumptions about affine ranges, aliasing, alignment, and memory effects. Each unsafe call must appear inside an explicit unsafe { ... } block. The caller must satisfy every requires clause; normal compilation trusts the contract.

export unsafe fn saxpy(x: slice<f64>, y: slice<f64>, n: u32) -> void
contract {
  requires n <= x.len && n <= y.len;
  requires noalias(x, y);
  requires aligned(x.data, 32);
  effects read(x), write(y);
}
{
}

For Native run or executable builds, --sanitize-contracts is an opt-in debugging aid. It does not turn an invalid ordinary unsafe call into defined behavior. See the complete language contract for the exact rules.

Repository reference links follow the main branch and may describe features newer than the latest downloadable release.

↵ open · esc close