# Memory Safety Layers

`Box<T>`, `Span<T>`, and `Ptr<T>` serve different roles: owned storage, a non-owning bounded view, and a raw typed address. Their types alone do not establish all lifetime, exclusivity, FFI, or target-specific requirements. Prefer an owned value or a view tied to a live owner for ordinary code; use raw pointers at a small, explicitly unsafe boundary.

| Type | Ownership and access | Essential boundary |
| --- | --- | --- |
| `Box<T>` | Owning heap-value surface | Follow move and borrowing rules; do not assume a particular internal strategy or zero overhead. |
| `Span<T>` | Non-owning pointer and element count | Bounds-checked `get` does not prove the backing storage is still alive or initialized. |
| `Ptr<T>` | Read-capable raw address | Reading requires a live, aligned, initialized pointee and an unsafe context. |
| `Ptr<T!>` | Raw address with writable-pointee capability | Writes additionally require valid writable storage and appropriate exclusive access. A `let!` binding alone does not confer this capability. |

## Raw Allocation Example

This complete example allocates three `i32` elements, initializes every element, makes a read-only span while the allocation remains live, then frees the original allocation exactly once. `fill` is itself `unsafe`: the caller must provide a live, aligned, writable range of at least `count` elements with exclusive write access. The raw span conversion must be justified separately.

```vex [raw-span.vx]
unsafe fn fill(p: Ptr<i32!>, count: usize): i32 {
    let! i: usize = 0;
    while i < count {
        p.writeAt(i, (i as i32) + 10);
        i = i + 1;
    }
    return 0;
}
fn main(): i32 {
    let p = Ptr.allocN<i32>(3);
    unsafe { fill(p, 3); }
    let view = unsafe { Span.of<i32>(p as Ptr<i32>, 3) };
    let value = match view.get(1) {
        Some(item) => *item,
        None => -1,
    };
    let out_of_bounds = view.get(3).isNone();
    unsafe { p.freeN(3); }
    if value != 11 || !out_of_bounds { return 1; }
    $println(value);
    return 0;
}
```

The program prints `11` and exits 0. The span is not used after `freeN(3)`. Do not generalize this fixture to foreign allocators: free an allocation only with its matching allocator, original pointer, and correct size. Raw pointer access and deallocation need their required unsafe context even if the pointer is non-null.

## A Rejected Read

The following is a **negative** example: on that same local binary, `vex lint` reports `E0133` for `p.read()` outside an unsafe context.

```vex [raw-read-rejected.vx]
fn main(): i32 {
    let p = Ptr.allocWith<i32>(42);
    let value = p.read();
    unsafe { p.free(); }
    return value;
}
```

A second **negative** example attempts a write through a read-capability pointer. The same local binary reports `E0308` for the unavailable `write` method, even inside `unsafe`:

```vex [readonly-write-rejected.vx]
fn main(): i32 {
    let p: Ptr<i32> = Ptr.allocWith<i32>(42);
    unsafe { p.write(7); }
    return 0;
}
```

`unsafe` permits operations whose preconditions the caller must prove; it does not grant writable-pointee capability.

A null check can reject a null address; it cannot prove a non-null pointer is allocated, aligned, initialized, in bounds, live, or unaliased. A dangling non-null pointer remains invalid. Likewise, wrapping an arbitrary address in a normal function does not make the function safe: its API must either establish those facts or expose an unsafe contract to its caller.

## More Reading

- [Span](span-t.md) — non-owning views and raw construction obligations
- [Typed pointers](ptr-t.md) — operations and deallocation
- [Unsafe](../advanced/unsafe.md) — unsafe boundaries
- [FFI native example](../ffi-first-native.md) — `.vxc` boundary and cleanup
- [Ownership](ownership.md)

<a id="the-four-layers"></a>
<a id="quick-decision-guide"></a>
<a id="layer-0-raw-pointers-ptr-t-ptr-t"></a>
<a id="layer-1-ptr-t-—-typed-pointer"></a>
<a id="layer-2-span-t-—-bounded-view"></a>
<a id="layer-3-box-t-—-owned-heap-value"></a>
<a id="combining-layers"></a>
<a id="layer-transitions"></a>
<a id="safety-comparison"></a>
<a id="best-practices"></a>
<a id="_1-start-at-the-highest-layer-drop-down-only-when-needed"></a>
<a id="_2-convert-upward-as-soon-as-possible"></a>
<a id="_3-use-span-for-function-interfaces"></a>
<a id="_4-keep-unsafe-at-the-boundary"></a>
<a id="see-also"></a>
