Memory without malloc and free · 13 min · free lesson

Pointers to References

A reference is a pointer the compiler checks: shared &T for reading, or one exclusive &mut T for writing, never both at once.

Core idea

At any point a value has either any number of shared borrows &T or exactly one mutable borrow &mut T, never both; a borrow lends access without transferring ownership.

C and Rust, side by side

C first points into the old buffer after realloc; AddressSanitizer reports a heap use after free.
#include <stdio.h>
#include <stdlib.h>

struct ivec { int *data; size_t len, cap; };

static void push(struct ivec *v, int x) {
    if (v->len == v->cap) {
        v->cap = v->cap ? v->cap * 2 : 1;
        v->data = realloc(v->data, v->cap * sizeof *v->data); /* may move */
    }
    v->data[v->len++] = x;
}

int main(void) {
    struct ivec v = {0};
    push(&v, 1);
    int *first = &v.data[0];  /* a pointer into the buffer */
    push(&v, 2);              /* realloc may have moved the buffer */
    printf("%d\n", *first);   /* ASan: heap-use-after-free */
    free(v.data);
    return 0;
}
Rust The value is copied out before push, and sum borrows v for reading only, so the later push is allowed.
fn sum(values: &[i32]) -> i32 { // a shared borrow: read-only access
    values.iter().sum()
}

fn main() {
    let mut v = vec![1];
    let first = v[0];   // copy the i32 out instead of keeping a borrow
    v.push(2);          // needs `&mut v`: no other borrow may be in use
    println!("{first}");
    let total = sum(&v); // lend `v` for reading; main still owns it
    v.push(3);
    println!("{total} {v:?}");
}
What changes
CRust
Any number of T * may read and write at the same time.Many &T readers or one &mut T writer at a time; a conflict is E0502.
restrict promises no aliasing, unchecked.&mut T is exclusive, and the compiler checks it.
A pointer may be NULL or dangle; callers check by hand.A reference is never null and cannot outlive its value.

Understand it

The C program keeps int *first into a dynamic array and then pushes. realloc may move the buffer, so first can dangle: AddressSanitizer reports heap-use-after-free, while a plain build may print the right number by luck. The bug is not the pointer itself but the combination of a reader that keeps a pointer and a writer that changes the buffer it points into.

Rust references are pointers with two rules that the compiler enforces. &T is shared: any number may exist, and none of them can mutate the value. It is like const T *, plus the guarantee that nobody else mutates the value while the borrow is in use. &mut T is exclusive: while it is in use, no other reference to the value may be used, which is what C's restrict promises and never checks. v.push(2) needs &mut v, so with first = &v[0] still in use, rustc reports E0502.

A borrow lasts until its last use, not until the end of the scope. Moving the println! above the push, or copying the i32 out with let first = v[0];, removes the conflict. References are never null and always point at a live value, so the defensive if (!p) return -1; at the top of a C function disappears for references; Option<&T> is the type when absence is possible.

Borrowing is also how a function reads data without taking ownership: fn sum(values: &[i32]) reads the caller's vector and leaves it with the caller. The aliasing bug in the challenge's C original, append_doubled(v, v->data, v->len), cannot be written in Rust: a &mut dst and a &dst in the same call are rejected.

The C habit, written in Rust

This is how the C version usually looks on a first attempt in Rust. Predict what rustc says before you read the explanation.

fn main() {
    let mut v = vec![1];
    let first = &v[0];
    v.push(2);
    println!("{first}");
}

Practise this code in Playground ↗

Try it

Port the commented C function: append_doubled pushes twice each value of src onto the end of dst and leaves src with the caller.

What success looks like: Values are appended after the existing ones, an empty src changes nothing, and src is still usable after the call.

Check your understanding

Why does rustc reject let first = &v[0]; v.push(2); println!("{first}");?

Reveal the answer
  1. v[0] cannot be borrowed because i32 is Copy
  2. first is a shared borrow still in use when push needs a mutable borrow of v
  3. push takes v by value, so v has moved
  4. Elements of a vector cannot be borrowed; you must use an index

The shared borrow lives until the println!. Print before pushing, or copy the value out with let first = v[0];, and the mutable borrow no longer overlaps it.

Go deeper

Common misconception: “A shared reference is just const T *.”

const T * only stops you writing through that pointer; other code may still change the value. &T also guarantees that nothing mutates the value while the borrow is in use (outside interior-mutability types such as Cell), which is why the compiler can reject the push.

  1. List the borrows: Mark every & and &mut, including implicit ones such as the &mut v that v.push takes.
  2. Find each last use: A borrow ends at its last use; draw a line from where it is created to that point.
  3. Look for overlap: A &mut that crosses a live & is E0502; reorder the code or copy the value out.

Transfer challenge: Call append_doubled(&mut v, &v) in your own main and read which two borrows rustc names; then make it compile with an explicit copy, let snapshot = v.clone();.

Connections

  • From malloc/free to Ownership: One owner frees, exactly once
  • Pointer + Length to Slices: A view that carries its own bounds
Side-by-side comparison: the C version on the left, the Rust version on the right, then 3 rows naming what changes.
Pointers to References: the same task in C and in Rust, with the differences that matter.
Learn this lesson with AI

Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.

I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools.
Lesson: Pointers to References (courseId "rust-for-c-developers", lessonId "c-pointers-to-references")
Link: https://crabrix.com/learn/rust-for-c-developers/c-pointers-to-references/
Goal: At any point a value has either any number of shared borrows &T or exactly one mutable borrow &mut T, never both; a borrow lends access without transferring ownership.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=rust-for-c-developers/c-pointers-to-references) and I will write the code there.
Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.

In Claude Code, Codex or Cursor, paste it into a chat with Crabrix Academy connected. On a phone, the Claude and ChatGPT apps open the same links.