# Pointers and Low-Level Memory

Vex exposes raw pointers for FFI, allocators, runtimes, and memory-mapped I/O.
Most code should use ownership, references, and bounds-aware views instead.

## Choose the narrowest abstraction

| Tool | Bounds | Ownership | Use it for |
| --- | --- | --- | --- |
| `&T` / `&T!` | one valid value | borrowed | ordinary safe access |
| `Span<T>` | checked extent | borrowed | contiguous views and slicing |
| `Ptr<T>` | unchecked | non-owning raw handle | typed FFI and allocator work |
| `RawBuf` | unchecked byte offsets | non-owning raw handle | binary layouts and runtime internals |
| `Ptr<Opaque>` | unchecked | non-owning raw handle | opaque C object-pointer boundaries |

`Ptr<T>` and `RawBuf` do not make invalid memory safe. They make units,
mutability, and intent explicit. `Ptr<T>` is represented as a target pointer;
that representation alone says nothing about the cost of allocation, copying
or a particular access pattern.

## Raw pointer forms

- `Ptr<T>` is a readable raw pointer to `T`.
- `Ptr<T!>` carries writable-pointee capability.
- `Ptr<Opaque>` is an opaque object pointer, similar to C's `void*`.

Legacy Vex spellings `*T`, `*T!`, and `ptr` are rejected by normal semantic
analysis. Existing source can be migrated with
`vex lint --fix --only pointer_migration`.

Dereference requires an unsafe boundary:

```vex
let value = 10
let raw = &value as Ptr<i32>
let loaded = unsafe { raw.read() }
```

The programmer must prove non-nullness, alignment, initialization, lifetime,
aliasing validity, and sufficient allocation extent.

## Typed raw access with `Ptr<T>`

Save the following as `raw-values.vx`. It checks allocation, initializes all
three elements, reads them while the storage is live, and frees it once:

```vex [raw-values.vx]
fn main(): i32 {
    let values = Ptr.allocN<i32>(3);
    if values == Ptr.nullMut<i32>() { return 1; }
    let result = unsafe {
        values.writeAt(0, 10);
        values.writeAt(1, 20);
        values.writeAt(2, 30);
        let value = (values as Ptr<i32>).readAt(1);
        values.freeN(3);
        value
    };
    $println(result);
    return if result == 20 { 0 } else { 2 };
}
```

Run `vex run raw-values.vx`. Expected output is `20`, with exit status 0.
Allocation failure returns 1 before any access. The example uses integers;
raw allocation of a type with a destructor also requires a deliberate
initialization and destruction protocol.

Pointer arithmetic is element-based: `values.add(2)` advances by two `i32`
elements, not two bytes. The raw handle carries no allocation extent or
lifetime. After `freeN`, every pointer or view into that allocation is invalid.

## Bounds-aware views with `Span<T>`

Construct a raw span only while its backing storage is live and initialized.
All uses of the span and references obtained from it must end before the
storage is freed, reallocated or incompatibly mutated. Prefer a container's
`asSpan()` when the container already owns the storage. The complete
[Span example](../memory/span-t.md) demonstrates this relationship without
manual deallocation.

## Byte-oriented access with `RawBuf`

`RawBuf` is a non-owning byte-addressed accessor. Its `load<T>(offset)` and
`store<T>(offset, value)` use byte offsets; the `loadAt`/`storeAt` forms use
element strides. Wrapping a pointer does not validate its extent,
initialization or aliasing. A mutable `RawBuf` binding alone does not prove
exclusive write access to the memory.

Use the complete [raw allocation example](../memory/safety.md#raw-allocation-example)
for allocation, access and cleanup in one scope. Do not reuse a pointer from
an earlier example after that example has freed it.

## Compiler-owned memory primitives

The embedded VexArch prelude implements these APIs using a small set of
compiler-owned runtime primitives. Those primitives are **prelude-only** and
normal Vex source must not call them directly.

This boundary is deliberate:

- application code receives typed, reviewable APIs;
- ownership-sensitive writes stay centralized;
- the compiler can change lowering without expanding the public surface;
- unsafe code does not become a collection of unstructured intrinsic calls.

If a missing operation seems to require direct compiler access, extend the
appropriate prelude abstraction instead of bypassing it.

## FFI example

Foreign declarations belong in a `.vxc` boundary in user packages. The
[first native bridge](../ffi-first-native.md) gives a complete `.vxc`/`.vx`
example with null checks, explicit ownership and cleanup on both success and
failure. It also shows the C implementation and manifest used in its test.

Do not call `Ptr.free()` for memory owned by a foreign allocator unless that
allocator is explicitly compatible with Vex's allocator. The allocator that
creates a block must also destroy it.

## Practical rules

1. Use references and owned containers in ordinary code.
2. Use `Span<T>` when an extent is known.
3. Use `Ptr<T>` for typed raw handles and element offsets.
4. Use `RawBuf` for byte layouts.
5. Keep raw pointers and allocator pairing at the boundary.
6. Never manufacture addresses through integer arithmetic when a typed prelude
   operation expresses the same intent.

## See also

- [`Ptr<T>`](../memory/ptr-t.md)
- [`Span<T>`](../memory/span-t.md)
- [RawBuf](../memory/rawbuf.md)
- [Memory Prelude](../memory/mem-prelude.md)
- [FFI](../ffi.md)
- [Unsafe](unsafe.md)
