Rust at a glance · 12 min · free lesson

What Safe Rust Rules Out

Safe Rust rules out the memory and thread bugs that are undefined behaviour in C, but not leaks, deadlocks, panics or wrong logic.

Core idea

Safe Rust has no undefined behaviour: use after free, double free, dangling references, out-of-bounds access, null dereference, uninitialised reads and data races are rejected or checked; leaks, deadlocks, panics, logic errors and wrapping arithmetic in release builds are not.

C and Rust, side by side

C Four undefined behaviours that compile without a warning; sanitizers report a stack overflow, a use after free, a null load and a double free.
#include <stdio.h>
#include <stdlib.h>

/* Every case compiles cleanly with -Wall -Wextra.
   Every case except 0 is undefined behaviour when it runs. */
int main(int argc, char **argv) {
    int which = argc > 1 ? atoi(argv[1]) : 0;
    int xs[3] = {1, 2, 3};
    int *null = NULL;
    int *heap = malloc(sizeof *heap);
    if (!heap) return 1;
    *heap = 7;
    if (which == 1) printf("%d\n", xs[which + 2]);           /* out of bounds */
    if (which == 2) { free(heap); printf("%d\n", *heap); }   /* use after free */
    if (which == 3) printf("%d\n", *null);                   /* null dereference */
    if (which == 4) free(heap);                              /* the first free... */
    if (which != 2) free(heap);                              /* ...and a double free */
    printf("case %d done\n", which);
    return 0;
}
Rust A checked index, a move instead of a second owner, Option instead of null, explicit wrapping, and a leak that is wasteful but safe.
fn main() {
    let xs = [1, 2, 3];
    let i = std::env::args().count() + 2;       // 3 when run without arguments
    println!("{:?}", xs.get(i));                // checked access: None
    let heap = Box::new(7);
    let owner = heap;                           // moved: `heap` is no longer usable
    println!("{owner}");
    let missing: Option<&i32> = None;           // no null references, only Option
    println!("{}", missing.copied().unwrap_or(0));
    let sum = 200u8.wrapping_add(100);          // wrapping you asked for: 44
    println!("{sum}");
    let leaked: &'static mut i32 = Box::leak(Box::new(1)); // a leak is safe
    *leaked += 1;
    println!("{leaked}");
}
What changes
CRust
Use after free, double free and dangling pointers compile and are undefined.Ownership and borrow checking reject them at compile time.
Out-of-bounds reads and NULL dereferences are undefined.Indexing is bounds-checked (a defined panic); absence is Option, never a null reference.
Reading an uninitialised variable is at most a warning.Every binding must be initialised on every path before it is read (E0381).
Leaks, deadlocks and logic errors are the programmer's problem.They still are: safe Rust excludes undefined behaviour, not bugs.

Understand it

In C, executing an undefined operation makes the whole program meaningless, and the optimiser is allowed to assume it never happens. The example's four cases compile without a single warning under -Wall -Wextra; each one fails only when it runs, and only a sanitizer build says why: stack-buffer-overflow, heap-use-after-free, a load of a null pointer and attempting double-free.

Safe Rust closes each of these by construction. Ownership means one owner frees each value once, so double free and use after free cannot be written. Borrow checking means a reference cannot outlive its value or overlap a writer. References are never null; absence is Option. A binding must be initialised on every path before it is read, or the program is rejected with E0381. Send and Sync, together with borrowing, make data races a compile error. Indexing is the one run-time check: xs[i] with a bad index panics, and xs.get(i) returns None, so an out-of-bounds read never touches the neighbouring memory.

"Safe" means free of undefined behaviour, not correct. Safe Rust can still leak memory (Box::leak, mem::forget and Rc cycles are all safe), deadlock on two Mutexes taken in different orders, compute the wrong answer, run out of memory or stack, and panic. A panic is defined behaviour: the thread unwinds and runs destructors, or the process aborts if it is configured to. Integer overflow is defined too, but in release builds it wraps unless you choose checked_ or keep overflow-checks on.

unsafe re-enables specific powers that safe code lacks: dereferencing raw pointers, calling unsafe functions including every C function, accessing mutable statics, implementing unsafe traits and reading union fields. Inside those blocks every C undefined behaviour is possible again, and the guarantee for the whole program rests on each unsafe block being right. That is why such blocks are kept small and documented; a later lesson shows how.

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 total: i32;
    let ready = std::env::args().count() > 1;
    if ready {
        total = 10;
    }
    println!("{total}");
}

Practise this code in Playground ↗

Try it

Run the C program's cases under a sanitizer in your head, match each one to the Rust rule that excludes it, then decide what the practice program needs before it compiles.

What success looks like: You can name the Rust mechanism behind each excluded C bug, and list three kinds of bug safe Rust still allows.

Check your understanding

Which of these can a program written entirely in safe Rust still do?

Reveal the answer
  1. Read a freed heap buffer through a stale reference
  2. Index one element past the end of an array without being stopped
  3. Dereference a null reference
  4. Leak memory with Box::leak or deadlock on two Mutexes

Leaks and deadlocks are bugs, not undefined behaviour, so safe Rust allows them. The other three are rejected at compile time or stopped by a bounds-check panic.

Go deeper

Common misconception: “If it compiles in Rust, it is correct.”

If it compiles without unsafe, it has no undefined behaviour. It can still leak, deadlock, panic or compute the wrong result; the compiler removes a class of bugs, not the need for tests.

  1. List the undefined cases: For a C function, write down every place it relies on a pointer being valid, an index being in range or a variable being set.
  2. Match the mechanism: Ownership, borrowing, Option, initialisation checks, bounds checks and Send/Sync each exclude one of them in safe Rust.
  3. Keep the remaining risks: Leaks, deadlocks, panics, overflow policy and logic still need tests and review, as in C.

Transfer challenge: Write a safe Rust program that deadlocks with two Mutexes locked in opposite orders by two threads, then fix it with one global lock order.

Connections

  • What Rust Is, from C: Native code and the same machine, with checks before it runs
  • Reading rustc Diagnostics: Compile-time errors instead of run-time crashes
Side-by-side comparison: the C version on the left, the Rust version on the right, then 4 rows naming what changes.
What Safe Rust Rules Out: 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: What Safe Rust Rules Out (courseId "rust-for-c-developers", lessonId "c-what-safe-rust-rules-out")
Link: https://crabrix.com/learn/rust-for-c-developers/c-what-safe-rust-rules-out/
Goal: Safe Rust has no undefined behaviour: use after free, double free, dangling references, out-of-bounds access, null dereference, uninitialised reads and data races are rejected or checked; leaks, deadlocks, panics, logic errors and wrapping arithmetic in release builds are not.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=rust-for-c-developers/c-what-safe-rust-rules-out) 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.