Crabrix blog

Rust for C developers: malloc and free rules the compiler checks

Rust for C developers: how ownership, Drop, borrows, lifetimes and slices turn the malloc and free contract into compiler checks, with tested C and Rust.

Rust for C developers starts with the same machine

If you write C, you already know most of what Rust does at run time. This guide to Rust for C developers follows the free Crabrix bridge course, Rust for C Developers: twenty lessons that each put a C habit next to its Rust equivalent and name exactly what changes. The thread through all of them is memory. In C, the rules about who calls free, how long a pointer stays valid and how big a buffer is are kept in comments and code review. Rust writes them into types and checks them before the program runs.

Moving from C to Rust means a compiler that asks for the proofs you used to keep in your head, not a new machine. Below, Rust vs C memory management is taken one contrast at a time, ending with a porting checklist.

Every Rust program here was compiled with rustc 1.99.0 and --edition 2024 on an aarch64 Mac and run; outputs and errors are quoted from those runs. The C programs were compiled with Apple clang 21 and -Wall -Wextra, and the deliberately buggy ones were run again under AddressSanitizer.

An orange paper crab engineer hands a brass key with a tag reading OWNER across a workbench covered in glowing amber and cyan memory blocks
Original generated illustration: ownership as a key that one owner holds and hands over, above a workbench of heap allocations.

Sources: What is ownership? (The Rust Programming Language)

Explore in Crabrix: Rust for C Developers course · What Rust Is, from C

Stack and heap work the way you expect

Rust has no garbage collector, no virtual machine and no interpreter. rustc lowers the program to LLVM IR, LLVM emits machine code as it does for clang, and the platform linker produces an ordinary executable. Locals live in stack frames, Box, Vec and String allocate on the heap through the system allocator, and structs have a size you can ask for.

The example is adapted from the course's first lesson. size_of::<Point>() printed 8, as sizeof(struct point) would. Box::new(on_stack) does the work of malloc plus a copy, and the run printed Box<Point> is 8 bytes, &Point is 8 bytes: a box is a single pointer, with no reference count beside it. The difference is the closing brace, where the compiler frees the box exactly once because its owner goes out of scope. Nothing watches pointers at run time; ownership and borrowing are checked in the compiler and cost nothing in the binary.

#[derive(Clone, Copy)]
struct Point {
    x: i32,
    y: i32,
}

fn main() {
    let on_stack = Point { x: 1, y: 2 };  // a stack slot, as in C
    let mut on_heap = Box::new(on_stack); // malloc + copy, with one owner
    on_heap.x = 10;
    let alias = &on_heap;                 // a pointer the compiler tracks
    println!("{} {} {} {}", on_stack.x, alias.x, alias.y, size_of::<Point>());
    println!("Box<Point> is {} bytes, &Point is {} bytes", size_of::<Box<Point>>(), size_of::<&Point>());
}                                         // the Box is freed here, exactly once

Sources: std::mem::size_of · std::boxed::Box

Explore in Crabrix: What Rust Is, from C · What Rust Is (Rust Basics)

Ownership is the malloc and free contract made explicit

Every C codebase has an ownership policy, even if nobody wrote it down: the function that calls malloc frees, unless a comment says the callee takes over. Get it wrong and you have a leak, a use after free or a double free.

The C program below is deliberately buggy. archive() frees its argument, nothing in void archive(char *) says so, and main frees the same pointer again. It compiled without a warning under -Wall -Wextra. The plain macOS build was killed by a trap inside free (exit status 133), and only the AddressSanitizer build said why: attempting double-free, at line 16.

Rust moves the policy into the type. String, Vec<T> and Box<T> own their heap memory. A parameter of type String takes ownership; a parameter of type &str borrows. One value has one owner, a move transfers ownership and ends the old binding, and the final owner frees the value when it goes out of scope.

A move is cheap: it copies the handle (for a String, a pointer, a length and a capacity) and treats the source as uninitialised; only .clone() copies heap data. A struct that owns a Vec cannot be Copy, so C's shallow struct copy becomes a move, and one buffer keeps one owner.

/* Deliberately buggy: a double free that compiles without a warning. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* Takes ownership and frees the report. Only this comment says so. */
static void archive(char *report) {
    printf("archived %s\n", report);
    free(report);
}

int main(void) {
    char *report = strdup("q3-summary");
    if (!report) return 1;
    archive(report);
    free(report);                 /* ASan: attempting double-free */
    return 0;
}
Infographic with a C column listing malloc, free and pointer, each linked by an arrow to a Rust column listing owner, drop and borrow
Original generated infographic: malloc maps to an owner, free to drop, and a raw pointer to a checked borrow.

Sources: malloc(3) and free(3), Linux manual page · AddressSanitizer, Clang documentation

Explore in Crabrix: From malloc/free to Ownership · Ownership (Academy) · Struct Copies: Copy and Clone

Drop replaces free and the goto cleanup chain

The Rust version needs no free at all. archive(report) moves the String into the function, which frees it on return. There is nothing to forget on an early return and nothing to call twice.

The second half shows the order. Three Noisy values implement Drop, Rust's destructor hook, and the run printed archived q3-summary, end of main, then drop file, drop lock and drop log. Locals drop in reverse declaration order, like a careful goto cleanup chain, on every exit path: a return, an error passed up with ? or an unwinding panic.

The same mechanism closes files and releases locks. To free early, call drop(x), which moves the value into a function that does nothing with it. Calling a destructor method yourself is rejected with E0040, so a double free stays unwritable.

struct Noisy(&'static str);

impl Drop for Noisy {
    fn drop(&mut self) {
        println!("drop {}", self.0); // runs once, when the owner goes away
    }
}

fn archive(report: String) { // takes ownership; the String is freed here
    println!("archived {report}");
}

fn main() {
    let report = String::from("q3-summary");
    archive(report);             // moved: `report` can no longer be used
    let _log = Noisy("log");
    let _lock = Noisy("lock");
    let _file = Noisy("file");
    println!("end of main");
}                                // drops in reverse: file, lock, log

Sources: std::ops::Drop

Explore in Crabrix: Drop & Scope · Deref & Drop

Use after free becomes error E0382

Now add the C habit back and use the report after handing it over. rustc refuses, and the diagnostic has the anatomy every Rust error shares.

The first line gives the code and the rule, borrow of moved value. ^^^^^^ marks the primary span, where the rule is broken, and the ------ labels explain why: where the value moved, and that String is not Copy. The note: points at the parameter that takes ownership, and the help: proposes report.clone().

Treat help: as one change that would compile, not as the fix. If archive only reads the report, the note's suggestion is better: make the parameter &str so the caller keeps ownership and nothing is copied. Fix the first error and recompile before reading the rest. rustc --explain E0382 prints the rule offline.

$ cat archive.rs
fn archive(report: String) {
    println!("archived {report}");
}

fn main() {
    let report = String::from("q3-summary");
    archive(report);
    println!("{report}");
}
$ rustc --edition 2024 archive.rs
error[E0382]: borrow of moved value: `report`
 --> archive.rs:8:16
  |
6 |     let report = String::from("q3-summary");
  |         ------ move occurs because `report` has type `String`, which does not implement the `Copy` trait
7 |     archive(report);
  |             ------ value moved here
8 |     println!("{report}");
  |                ^^^^^^ value borrowed here after move
  |
note: consider changing this parameter type in function `archive` to borrow instead if owning the value isn't necessary
 --> archive.rs:1:20
  |
1 | fn archive(report: String) {
  |    -------         ^^^^^^ this parameter takes ownership of the value
  |    |
  |    in this function
help: consider cloning the value if the performance cost is acceptable
  |
7 |     archive(report.clone());
  |                   ++++++++

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0382`.

Sources: Error code E0382

Explore in Crabrix: Reading rustc Diagnostics · Reading rustc (Rust Basics)

Borrowing versus pointers: shared readers or one writer

A C pointer can read, write, alias and dangle, and its type does not say which. The second C example is again deliberately buggy: keep int *first into a growable array, push, then read through first after realloc may have moved the buffer. There were no warnings, the plain build printed 1 by luck, and AddressSanitizer reported heap-use-after-free on line 21.

Rust references are pointers with two enforced rules. &T is shared: any number may exist, and nothing mutates the value while they are in use, a guarantee const T * never gives. &mut T is exclusive: while it is in use, no other reference to the value may be used, which is what restrict promises and C never checks.

References are also never null, so the if (!p) return -1; guard disappears; Option<&T> is the nullable form, and it measured 8 bytes, the same as a plain reference.

/* Deliberately buggy: a pointer into a buffer that realloc may move. */
#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 */
        if (!v->data) exit(1);
    }
    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;
}

Sources: References and borrowing (The Rust Programming Language) · realloc, cppreference

Explore in Crabrix: Pointers to References · First References · Borrowing

The borrow checker guards the gate at compile time

Port the ivec example literally and rustc stops at the push. v.push(2) needs &mut v while first still holds a shared borrow that is used on the next line. That is E0502, and its three labels tell the story: where the reader starts, where the writer wants in, and where the reader is still in use.

A borrow lasts until its last use, not until the end of the block, so printing before the push, or copying the value out with let first = v[0];, fixes it. Two writers are refused the same way: two live &mut total borrows stopped the build with E0499. Passing &mut v and &v to one function, the aliasing that restrict forbids, was rejected with E0502.

The gate closes at compile time; the binary carries no lock or counter for these references. A design that needs the check at run time, such as a graph of shared nodes, uses RefCell, where a violation becomes a panic.

$ cat push.rs
fn main() {
    let mut v = vec![1];
    let first = &v[0];
    v.push(2);
    println!("{first}");
}
$ rustc --edition 2024 push.rs
error[E0502]: cannot borrow `v` as mutable because it is also borrowed as immutable
 --> push.rs:4:5
  |
3 |     let first = &v[0];
  |                  - immutable borrow occurs here
4 |     v.push(2);
  |     ^^^^^^^^^ mutable borrow occurs here
5 |     println!("{first}");
  |                ----- immutable borrow later used here

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0502`.
An orange paper crab gatekeeper at a toll gate lets a line of cyan arrows onto a bridge of memory blocks while a single amber arrow waits behind the barrier
Original generated illustration: the borrow checker lets many shared readers cross, and holds the one writer back until they are done.

Sources: Error code E0502 · Error code E0499

Explore in Crabrix: Mutable Borrows · Rc & RefCell

Lifetimes are the dangling-pointer check

A C function that returns a pointer into one of its arguments says so in a comment, if at all; const char *longer(const char *, const char *) carries none of it. The course's C version frees b and then prints the result. It compiled cleanly with -Wall -Wextra, and AddressSanitizer reported heap-use-after-free.

Rust writes the fact into the signature. fn longer<'a>(a: &'a str, b: &'a str) -> &'a str says the result is valid only while both inputs are, and the compiler checks every caller. Below, b is dropped at the end of the inner block while result still points into it, so the build stops with E0597.

An annotation describes a relationship; it never makes a value live longer, and returning a reference to a local is still rejected. Most signatures need none: with one reference input, as in fn first_word(line: &str) -> &str, elision ties the output to it. With several reference inputs and a reference output, rustc asks which one you return, with E0106.

$ cat longer.rs
fn longer<'a>(a: &'a str, b: &'a str) -> &'a str {
    if a.len() >= b.len() { a } else { b }
}

fn main() {
    let a = String::from("short");
    let result;
    {
        let b = String::from("much longer");
        result = longer(&a, &b);
    }
    println!("{result}");
}
$ rustc --edition 2024 longer.rs
error[E0597]: `b` does not live long enough
  --> longer.rs:10:29
   |
 9 |         let b = String::from("much longer");
   |             - binding `b` declared here
10 |         result = longer(&a, &b);
   |                             ^^ borrowed value does not live long enough
11 |     }
   |     - `b` dropped here while still borrowed
12 |     println!("{result}");
   |                ------ borrow later used here

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0597`.

Sources: Validating references with lifetimes (The Rust Programming Language) · Error code E0597

Explore in Crabrix: Dangling Pointers and Lifetimes · Lifetime Intuition

Slices replace a pointer and a length

C arrays decay to pointers at a function boundary, so the length travels separately. Compiling the course's C max_in with -Wall -Wextra gave one warning, -Wsizeof-array-argument, because sizeof xs inside the function is a pointer's size. Its i <= n off-by-one got no warning, and the plain build printed max = 9 after reading past the array.

A Rust slice &[T] is a fat pointer, the address and the length in one value. Arrays and vectors both coerce to it, len() is always right, and indexing is checked: xs[3] on a three-element array panicked with index out of bounds: the len is 3 but the index is 3. xs.get(3) returns None. The example printed max = Some(9), vec max = Some(8), tail max = Some(2), empty max = None and None.

Slicing makes a view, not a copy. A bounds check is a compare and a predictable branch, and the optimiser removes it when it can prove the index is in range, as iterator loops usually allow.

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];
    let v = vec![7, 3, 8, 1];
    println!("len = {}", xs.len());
    println!("max = {:?}", max_in(&xs));              // an array coerces to &[i32]
    println!("vec max = {:?}", max_in(&v));           // so does a Vec
    println!("tail max = {:?}", max_in(&xs[2..]));
    println!("empty max = {:?}", max_in(&xs[3..]));   // valid and empty
    println!("{:?}", xs.get(3));                      // checked access: None
}

Sources: The slice type (The Rust Programming Language) · Primitive type slice

Explore in Crabrix: Pointer + Length to Slices · Slices (Academy)

Box, Rc and Arc: choose by the number of owners

C has one heap pointer type and conventions on top of it; Rust names the common ones. Box<T> is the single owner of one allocation, like a struct node *next that frees its node. Rc<T> is shared ownership on one thread with a plain count, the refcount++ and release function C programs write by hand. Arc<T> uses an atomic count, so its handles may cross threads.

In the example, the boxed list summed to 3 and every node is freed when list goes out of scope. The Rc count fell from 2 to 1 when reader was dropped. Three threads each got an Arc clone and returned [20, 40, 60], and after joining the count was back to 1. Cloning either pointer copies a pointer and bumps a count; it never deep-copies the value.

Pick the narrowest that fits; the compiler holds the line, and moving an Rc into a thread failed with E0277. Neither pointer grants mutation: add RefCell on one thread, or a Mutex across threads, whose guard releases the lock when dropped, even on an early return.

use std::rc::Rc;
use std::sync::Arc;
use std::thread;

// Box: each node owns the next one, like a malloc'd `struct node *next`.
enum List {
    Node(i32, Box<List>),
    End,
}

fn sum(list: &List) -> i32 {
    match list {
        List::Node(value, next) => value + sum(next),
        List::End => 0,
    }
}

fn main() {
    let list = List::Node(1, Box::new(List::Node(2, Box::new(List::End))));
    println!("box sum = {}", sum(&list)); // the whole list is freed when `list` goes

    // Rc: several owners on one thread; the last one to leave frees the value.
    let config = Rc::new(String::from("verbose"));
    let reader = Rc::clone(&config); // copies a pointer and bumps a count
    println!("rc owners = {}", Rc::strong_count(&config));
    drop(reader);
    println!("rc owners = {}", Rc::strong_count(&config));

    // Arc: the same idea with an atomic count, so handles may cross threads.
    let table = Arc::new(vec![10, 20, 30]);
    let handles: Vec<_> = (0..3)
        .map(|i| {
            let table = Arc::clone(&table);
            thread::spawn(move || table[i] * 2)
        })
        .collect();
    let doubled: Vec<i32> = handles.into_iter().map(|h| h.join().unwrap()).collect();
    println!("arc results = {doubled:?}, owners now = {}", Arc::strong_count(&table));
}

Sources: std::rc::Rc · std::sync::Arc

Explore in Crabrix: Box<T> · Box, Rc, and Arc (interview question) · pthreads to std::thread · Shared State

Strings are not char pointers

A C string is a byte array ended by a NUL; its length is a scan and strcpy trusts the destination. Compiling the course's C example, clang caught one case statically, 'strcpy' will always overflow; destination buffer has size 8, but the source string has length 9 (including NUL byte), and the plain build was killed with exit status 133. Overflows with run-time lengths get no such warning.

String owns a heap buffer and stores its length and capacity, so len() is constant time and push_str grows the buffer instead of overflowing it. &str is a borrowed pointer and length. Both are always valid UTF-8, which changes counting: len() of café printed 5 bytes, as strlen would, while chars().count() printed 4, and to_uppercase() gave CAFÉ where byte-wise toupper leaves the é alone.

Indexing a string by an integer does not compile, and byte ranges must land on character boundaries: get(0..4) returned None because byte 4 is inside é. At the C boundary, CString adds the terminator and refuses an interior NUL; the run printed 18 bytes for the 17-byte name, and true for the rejection.

use std::ffi::CString;

fn main() {
    let word = "café";
    println!("len={} chars={}", word.len(), word.chars().count()); // bytes vs chars
    println!("{}", word.to_uppercase());                // CAFÉ: Unicode-aware
    println!("{:?} {:?}", word.get(0..3), word.get(0..4)); // byte 4 is inside 'é'

    let mut name = String::with_capacity(8);
    name.push_str("Margaret");                          // fits exactly; no NUL needed
    name.push_str(" Hamilton");                         // grows instead of overflowing
    println!("{name} ({} bytes)", name.len());

    // Crossing into C: a NUL-terminated copy, refused if the text contains a NUL.
    let for_c = CString::new(name.as_str()).expect("no interior NUL");
    println!("{} bytes with the terminator", for_c.as_bytes_with_nul().len());
    println!("interior NUL rejected: {}", CString::new("a\0b").is_err());
}

Sources: std::string::String · std::ffi::CString · strcpy, cppreference

Explore in Crabrix: char Arrays to Strings · Strings & UTF-8

Option and Result replace NULL, -1 and errno

C signals trouble out of band: NULL for absent, or -1 with the reason in errno, which must be cleared before calls such as strtol and read before the next call overwrites it. When -1 is also a valid result, only errno tells them apart.

Rust puts both cases in the return type. Option<T> is Some or None, Result<T, E> is Ok or Err, and the caller cannot reach the value without handling the other case. The example gives a C-style parse_port a named error type: ok_or turns absence into PortError::Missing, ? replaces the if (rc < 0) return rc; ladder, and u16::try_from refuses a value that does not fit instead of truncating it.

The run printed port 8080, no port given, not a number: invalid digit found in string for -1, and 70000 does not fit in a u16. Each error travels with its result, and no later call can overwrite it. Keep unwrap() and expect(), which turn failure into a panic, for tests and impossible states.

use std::fmt;
use std::num::ParseIntError;

#[derive(Debug)]
enum PortError {
    Missing,
    NotANumber(ParseIntError),
    OutOfRange(u32),
}

impl fmt::Display for PortError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            PortError::Missing => write!(f, "no port given"),
            PortError::NotANumber(e) => write!(f, "not a number: {e}"),
            PortError::OutOfRange(v) => write!(f, "{v} does not fit in a u16"),
        }
    }
}

// C: `int parse_port(const char *s)`, returning -1 and setting errno.
fn parse_port(text: Option<&str>) -> Result<u16, PortError> {
    let text = text.ok_or(PortError::Missing)?; // NULL becomes a named case
    let value: u32 = text.trim().parse().map_err(PortError::NotANumber)?;
    u16::try_from(value).map_err(|_| PortError::OutOfRange(value))
}

fn main() {
    for input in [Some("8080"), None, Some("-1"), Some("70000")] {
        match parse_port(input) {
            Ok(port) => println!("{input:?} -> port {port}"),
            Err(error) => println!("{input:?} -> error: {error}"),
        }
    }
}

Sources: errno(3), Linux manual page · Recoverable errors with Result (The Rust Programming Language)

Explore in Crabrix: NULL and errno to Option and Result · Option & Result · Handling Failure · Integer Overflow and Casts

unsafe and FFI are the honest boundary

Creating a raw pointer, *const T or *mut T, is safe; dereferencing it needs unsafe, as do calling foreign functions, accessing a mutable static and reading a union field. Inside the block, types, borrows and slice bounds are still checked. unsafe is your claim that invariants the compiler cannot see hold, written down in a # Safety section on each unsafe fn and a // SAFETY: comment on each block.

The example is a thin unsafe edge around safe code. sum_i32 is exported to C with #[unsafe(no_mangle)] and extern "C", and turns the C pointer and length into a slice with slice::from_raw_parts, whose obligations are what the C contract said in prose: non-null, aligned, n initialised elements, no mutation meanwhile. After that line it is ordinary bounds-checked Rust. In edition 2024, foreign declarations such as abs go in an unsafe extern "C" block.

#[repr(C)] gives Pair C's field order and padding, so its size was 8, like a C struct of a uint8_t and a uint32_t; without it Rust may reorder fields. The run printed 6 size=8 tag=7 value=42 abs=5. Keep unsafe blocks small, documented and tested, and review them as you reviewed every pointer in C.

use std::slice;

#[repr(C)] // C field order and padding: tag, 3 padding bytes, value
struct Pair {
    tag: u8,
    value: u32,
}

/// Callable from C as `int32_t sum_i32(const int32_t *xs, size_t n)`.
///
/// # Safety
/// `xs` must be non-null, aligned and point to `n` initialised `i32`s
/// that nothing mutates during the call.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn sum_i32(xs: *const i32, n: usize) -> i32 {
    // SAFETY: the caller upholds the contract documented above.
    let values = unsafe { slice::from_raw_parts(xs, n) };
    values.iter().sum() // from here on: ordinary, bounds-checked Rust
}

unsafe extern "C" {
    fn abs(x: i32) -> i32; // from the C library; the declaration is a promise
}

fn main() {
    let xs = [1, 2, 3];
    let p = Pair { tag: 7, value: 42 };
    // SAFETY: `xs` is a live array of 3 `i32`s, and `abs` has this C signature.
    let (total, magnitude) = unsafe { (sum_i32(xs.as_ptr(), xs.len()), abs(-5)) };
    println!("{total} size={} tag={} value={} abs={magnitude}", size_of::<Pair>(), p.tag, p.value);
}

Sources: Foreign Function Interface (The Rustonomicon) · Unsafe extern blocks (Edition Guide, Rust 2024) · Behavior considered undefined (The Rust Reference)

Explore in Crabrix: unsafe, Raw Pointers and FFI · unsafe Rust · Raw Pointers · FFI

What Rust does not prevent: leaks, deadlocks and logic bugs

Safe Rust excludes undefined behaviour: use after free, double free, dangling references, out-of-bounds access, null dereference, uninitialised reads and data races. The course's C program with four of these compiled without a warning; in safe Rust none of them can be written. That is not the same as correct.

Leaks are safe: Box::leak, mem::forget and reference-count cycles cannot corrupt memory. The example links two nodes with Rc in both directions; the run reported 2 owners each, and dropping both outside handles printed no free a and no free b. A Weak back link fixes the design because it does not own: upgrade() worked while the parent lived, free parent printed when it was dropped, and the next upgrade() returned nothing.

Deadlocks are safe too: two threads taking two Mutexes in opposite orders hang Rust as they hang C. A panic is defined behaviour. Integer overflow panics in debug builds and, by default, wraps in release builds unless you choose checked_, wrapping_ or saturating_ arithmetic. Wrong answers compile as well as right ones, so keep your tests.

use std::cell::RefCell;
use std::rc::{Rc, Weak};

struct Node {
    name: &'static str,
    next: RefCell<Option<Rc<Node>>>,
}

impl Drop for Node {
    fn drop(&mut self) {
        println!("free {}", self.name);
    }
}

fn node(name: &'static str) -> Rc<Node> {
    Rc::new(Node { name, next: RefCell::new(None) })
}

fn main() {
    // Two strong links in a cycle: safe Rust, and neither node is ever freed.
    let a = node("a");
    let b = node("b");
    *a.next.borrow_mut() = Some(Rc::clone(&b));
    *b.next.borrow_mut() = Some(Rc::clone(&a));
    println!("a owners = {}, b owners = {}", Rc::strong_count(&a), Rc::strong_count(&b));
    drop(a);
    drop(b); // no "free a" or "free b" follows: the cycle leaks

    // A Weak back link does not own, so the parent is freed on time.
    let parent = node("parent");
    let back: Weak<Node> = Rc::downgrade(&parent);
    println!("parent alive: {}", back.upgrade().is_some());
    drop(parent);
    println!("parent alive: {}", back.upgrade().is_some());

    // Box::leak is safe too: the memory is never returned to the allocator.
    let forever: &'static mut u32 = Box::leak(Box::new(1));
    *forever += 1;
    println!("leaked value = {forever}");
}

Sources: Behavior not considered unsafe (The Rust Reference) · Reference cycles can leak memory (The Rust Programming Language)

Explore in Crabrix: What Safe Rust Rules Out · Reference Cycles

A checklist for porting C code to Rust

Port one module at a time, keep the C tests, and let the compiler find the conventions you relied on.

First, run the C code under -fsanitize=address,undefined. Undefined behaviour found now is a bug you would otherwise port faithfully, and the outputs become the reference the Rust version must match.

Next, turn every ownership comment into a type. A pointer parameter that is consumed becomes T, Box<T>, Vec<T> or String; one that is only read becomes &T, &[T] or &str; one that is written becomes &mut T. A returned pointer becomes a value if the caller owns it, or a reference with a lifetime if it points into an argument.

Replace pointer-and-length pairs with slices, char * with String or &str, NULL with Option, and -1 plus errno with Result and an error enum. Tagged unions become enums, and match lists every place a new variant must be handled. Make integer conversions explicit with From, TryFrom or as.

Delete the cleanup code: free, goto cleanup and pthread_mutex_unlock become Drop, as long as each resource has one owner whose scope ends where the old cleanup ran. Keep extern declarations and raw-pointer conversions in one small module and expose only safe functions.

Finally, replace the Makefile with Cargo and keep -Werror discipline with #![deny(warnings)] or -D warnings in CI.

Sources: UndefinedBehaviorSanitizer, Clang documentation · The Cargo Book

Explore in Crabrix: Tagged Unions to Enums · Headers and make to Cargo

Learn it with the course, the Playground or your AI agent

Rust for C Developers is free on the web: 20 lessons in five units, from what Rust is to unsafe, FFI and threads. Each lesson sets the C program beside the Rust one, asks you to port a C function, and lists the Academy lessons it covers, such as Ownership, Borrowing and Slices. The bridge courses reach the iPhone and iPad app in the next app version, Crabrix 1.2.

Every lesson in the course opens a practice copy of its code in the Playground, which runs a real Rust compiler in your browser. They are among the 190 Academy lessons that gained practice copies this week, checked with rustc for wasm32-wasip1 and then in the Playground. A copy is a new, unsaved document and never overwrites a draft.

To learn with an AI agent, the Learn with your AI agent page connects Claude, Claude Code, Codex, Cursor or another MCP client to the read-only Academy server at https://crabrix.com/mcp/academy, with no sign-in. Its C developer prompt asks for memory management, ownership, borrowing, lifetimes and system programming, and the Rust for C Developers learning path has 45 steps: the 20 bridge lessons, then borrowing in depth, smart pointers, FFI and layout, unsafe contracts and threads with atomics. The agent's review is labelled AI reviewed; only the app's checks record progress.

Sources: Model Context Protocol

Explore in Crabrix: Rust for C Developers course · Learn Rust with your AI agent · Playground

Explore the free Crabrix lessons →