C and Rust, side by side
archive() frees its argument, so the caller's free is a double free that AddressSanitizer reports.#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");
archive(report);
free(report); /* ASan: attempting double-free */
return 0;
}
archive consumes report; the three Noisy values drop in reverse order (file, lock, log) after end of main.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
| C | Rust |
|---|---|
Who calls free is a comment-level convention. | The owner frees; ownership is in the type: String, Vec<T>, Box<T>. |
| Using a pointer after the callee freed it compiles. | Using a moved value is error E0382. |
Cleanup on every exit path, often goto cleanup in reverse order. | Locals drop in reverse declaration order on every exit path. |
Understand it
In C, ownership of a malloc result is a convention written in comments: who frees it, and when. Getting it wrong has three outcomes: a leak, a use after free or a double free. The example's archive() frees its argument and the caller frees it again. Nothing in void archive(char *) says the pointer is consumed, so the compiler cannot help; AddressSanitizer reports attempting double-free, and a plain macOS build is killed by a trap inside free.
Rust makes the convention part of the type. String, Vec<T> and Box<T> own their heap memory. A parameter of type String takes ownership: after archive(report) the value has moved, and any later use of report is error E0382, borrow of moved value. The value is freed once, by its final owner, when that owner goes out of scope. There is no free to call and none to forget on an early return.
A move copies only the handle (pointer, length and capacity) and then treats the source as uninitialised; nothing is deep-copied unless you call .clone(). Returning a value moves it out to the caller, which is how a Rust function hands back ownership, like a C function returning a pointer the caller must free.
Cleanup order is defined. At the end of a scope, the remaining locals drop in reverse declaration order, the order a careful goto cleanup chain releases resources. The Drop trait runs code at that point, so the same mechanism closes files and releases locks. drop(x) ends a value early by moving it into a function that does nothing with it.
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 archive(report: String) {
println!("archived {report}");
}
fn main() {
let report = String::from("q3-summary");
archive(report);
println!("{report}");
}
Try it
Port the commented C function: take_largest returns the longest buffer (the first one on a tie) without copying it, drops all the others, and returns None for an empty list.
What success looks like: The returned Vec has the same heap pointer as the buffer it came from, a tie returns the first longest buffer, and an empty list gives None.
Check your understanding
A function declares let _log = Noisy("log"); let _lock = Noisy("lock"); let _file = Noisy("file");. In which order do their Drop implementations run at its closing brace?
Reveal the answer
log,lock,file: declaration order- In an unspecified order, as with a garbage collector
file,lock,log: reverse declaration order- None of them run there: names starting with
_are dropped immediately
Remaining locals drop in reverse declaration order. A leading underscore only silences the unused-variable warning; _log still owns its value until the scope ends.
Go deeper
Common misconception: “Rust frees memory with a garbage collector, so cleanup happens at some later time.”
There is no collector. The compiler inserts the drop at a known point: the end of the final owner's scope, or the call to drop. That point is visible in the source, exactly where a careful C programmer would have called free.
- Find each owner: For each
String,VecorBox, name the binding that owns it on each line. - Mark the moves: Every by-value argument, assignment or return moves ownership; after it, the old name is unusable.
- Place the drops: At each closing brace, list the remaining owners in reverse declaration order.
Transfer challenge: Change archive to take &str so the caller keeps report, then return a String from a helper function and trace which binding finally frees it.
Connections
- From for(;;) to Ranges: Ranges, iterators and loop with a value
- Pointers to References: Shared or exclusive, checked at compile time

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: From malloc/free to Ownership (courseId "rust-for-c-developers", lessonId "c-malloc-free-to-ownership") Link: https://crabrix.com/learn/rust-for-c-developers/c-malloc-free-to-ownership/ Goal: One value has one owner; a move transfers ownership and ends the old binding, and the remaining owners drop in reverse declaration order at the end of their scope. Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=rust-for-c-developers/c-malloc-free-to-ownership) 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.