Memory without malloc and free · 11 min · free lesson

Pointer + Length to Slices

A slice &[T] is a pointer and a length in one value, so functions receive their bounds and every index is checked.

Core idea

A slice borrows a contiguous range of another value's elements; it allocates nothing, and indexing past its length panics instead of reading out of bounds.

C and Rust, side by side

C sizeof on an array parameter gives the pointer size, and i <= n reads past the end, which AddressSanitizer reports as a stack buffer overflow.
#include <stdio.h>

static int max_in(const int xs[], size_t n) {  /* xs is really const int * */
    printf("sizeof xs = %zu\n", sizeof xs);      /* pointer size, not the array */
    int best = xs[0];
    for (size_t i = 1; i <= n; i++)              /* off by one: reads xs[n] */
        if (xs[i] > best) best = xs[i];
    return best;
}

int main(void) {
    int xs[] = {4, 9, 2};
    printf("max = %d\n", max_in(xs, sizeof xs / sizeof xs[0]));
    return 0;
}
Rust max_in takes a slice, so the length cannot be wrong; an empty slice gives None, and get(3) is None instead of a read past the end.
fn max_in(xs: &[i32]) -> Option<i32> { // the slice carries its length
    let mut best = *xs.first()?;          // empty slice: None, not a read of xs[0]
    for &x in &xs[1..] {                  // a subslice: a view, nothing copied
        if x > best {
            best = x;
        }
    }
    Some(best)
}

fn main() {
    let xs = [4, 9, 2];
    println!("len = {}", xs.len());
    println!("max = {:?}", max_in(&xs));
    println!("tail max = {:?}", max_in(&xs[2..]));
    println!("empty max = {:?}", max_in(&xs[3..])); // valid and empty
    println!("{:?}", xs.get(3));                    // checked access: None
}
What changes
CRust
Pointer and length are separate arguments that can disagree.&[T] carries both; len() is always the real length.
xs[n] reads past the end without a check.xs[n] panics; xs.get(n) returns None.
Arrays decay; sizeof inside the callee is the pointer size.Arrays and Vecs coerce to &[T] and keep their length.

Understand it

C arrays decay to pointers at a function boundary, so the length has to travel separately and nothing ties the two together. Inside max_in, sizeof xs is the size of a pointer, which clang flags with -Wsizeof-array-argument, and the i <= n off-by-one reads one element past the array: AddressSanitizer reports a stack-buffer-overflow.

A Rust slice &[i32] is a fat pointer: the address and the length together. xs.len() is always right, and xs[i] checks i < len and panics with index out of bounds: the len is 3 but the index is 3 instead of reading the neighbour. When an index may be out of range, xs.get(i) returns an Option. Arrays, vectors and other slices all coerce to &[T], so one function serves all of them.

Slicing creates a view, not a copy: &xs[1..], xs.split_at(mid) and xs.windows(2) borrow the same memory with different bounds. A function that returns a &[i32] derived from its &[i32] argument is returning a range of the caller's data, and the compiler ties the result's validity to that input, so it cannot outlive the buffer. &str is the same idea for UTF-8 text.

Bounds checks are cheap and are often removed when the compiler can see the index stays in range, which is common in iterator loops. When profiling shows a real cost, iterate instead of indexing, or slice once up front so the later indexes are provably in bounds.

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 xs = [4, 9, 2];
    let mut best = xs[0];
    for i in 1..=xs.len() {
        if xs[i] > best {
            best = xs[i];
        }
    }
    println!("{best}");
}

Practise this code in Playground ↗

Try it

Port the commented C function: longest_run returns the longest run of equal neighbouring values as a subslice of xs, the first one on a tie, and an empty slice for empty input.

What success looks like: [5, 5, 1, 7, 7, 7] gives [7, 7, 7] even though that run ends the slice, a tie returns the first run, and the result points into the input.

Check your understanding

What does the return type of fn longest_run(xs: &[i32]) -> &[i32] promise?

Reveal the answer
  1. A new heap-allocated copy of the run
  2. A pointer that may outlive xs
  3. A fixed-size array of the run's length
  4. A borrowed view into xs, valid only while xs is

With one reference input, the result borrows from it: a range of the caller's elements, with no allocation, tied to the input's lifetime.

Go deeper

Common misconception: “Bounds checking makes slices slow, so real code uses raw pointers.”

The check is a comparison and a predictable branch, and it disappears when the compiler can prove the index is in range, as it usually can in iterator loops. Measure first; idiomatic Rust rarely needs get_unchecked.

  1. Fuse the arguments: Replace each (const T *p, size_t n) pair with one &[T], and each writable pair with &mut [T].
  2. Replace index arithmetic: Turn p + i, n - i into &xs[i..], and loops that compare neighbours into windows(2) or an index loop over 1..xs.len().
  3. Check the ends: Test an empty slice, a single element and a run that touches the last element.

Transfer challenge: Write fn split_header(packet: &[u8]) -> Option<(&[u8], &[u8])> that returns the first 4 bytes and the rest, or None when the packet is shorter than 4 bytes.

Connections

  • Pointers to References: Shared or exclusive, checked at compile time
  • Dangling Pointers and Lifetimes: The compiler checks what the comment promised
Side-by-side comparison: the C version on the left, the Rust version on the right, then 3 rows naming what changes.
Pointer + Length to Slices: 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: Pointer + Length to Slices (courseId "rust-for-c-developers", lessonId "c-pointer-length-to-slices")
Link: https://crabrix.com/learn/rust-for-c-developers/c-pointer-length-to-slices/
Goal: A slice borrows a contiguous range of another value's elements; it allocates nothing, and indexing past its length panics instead of reading out of bounds.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=rust-for-c-developers/c-pointer-length-to-slices) 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.