C and Rust, side by side
b; after free(b), printing it is a heap use after free that AddressSanitizer reports.#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Returns a pointer into a or b. Which one, and for how long, is up to the caller. */
static const char *longer(const char *a, const char *b) {
return strlen(a) >= strlen(b) ? a : b;
}
int main(void) {
char *a = strdup("short");
char *b = strdup("much longer");
const char *result = longer(a, b);
free(b); /* ends b's storage; result still points into it */
printf("%s\n", result); /* ASan: heap-use-after-free */
free(a);
return 0;
}
longer needs 'a because it has two reference inputs; first_word has one, so elision ties its result to line.// `'a`: the result borrows from `a` or `b`, so it is valid while both are.
fn longer<'a>(a: &'a str, b: &'a str) -> &'a str {
if a.len() >= b.len() { a } else { b }
}
// One reference input: elision ties the result to `line`, no annotation needed.
fn first_word(line: &str) -> &str {
line.split_whitespace().next().unwrap_or("")
}
fn main() {
let a = String::from("short");
{
let b = String::from("much longer");
let result = longer(&a, &b);
println!("{result}"); // fine: b is still alive here
}
println!("{}", first_word(" hello world"));
}
| C | Rust |
|---|---|
| Which argument a returned pointer refers to lives in a comment. | The signature's lifetimes say it, and the compiler checks every caller. |
| Freeing the source while a pointer into it remains compiles. | Using a borrow after its source is dropped is error E0597. |
| Returning the address of a local is only a warning. | Returning a reference to a local is always an error. |
Understand it
A C function that returns a pointer into one of its arguments documents the relationship in a comment: the result points into a or b. The caller in the example frees b and then prints the result, and AddressSanitizer reports heap-use-after-free. Nothing in const char *longer(const char *, const char *) carries the fact that matters.
Rust writes that fact into the signature. fn longer<'a>(a: &'a str, b: &'a str) -> &'a str says the result borrows from the inputs and may be used only while both borrows are valid. The compiler then checks every caller: using result after b has been dropped is error E0597, b does not live long enough.
Most signatures need no annotation, because of elision. With exactly one reference input, the output borrows from it: fn first_word(line: &str) -> &str. With a &self method, the output borrows from self. With two reference inputs and a reference output there is no default, so rustc asks with E0106, missing lifetime specifier, because it cannot know which input you return.
An annotation describes a relationship. It does not make anything live longer and cannot turn a dangling pointer into a valid one; returning a reference to a local, like return buf; for a stack array, is still rejected. Choose lifetimes that state what the code really does: if the result only ever points into line, only line should share 'a. Tying prefix to it as well would force callers to keep prefix alive for no reason.
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 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}");
}
Try it
Port the commented C functions, keeping the lifetimes in the starter: after_prefix returns the rest of line after prefix, or None, and borrows only from line; longer returns the input with more bytes, a on a tie.
What success looks like: The result of after_prefix stays usable after prefix is dropped, a line shorter than its prefix gives None instead of a panic, and a tie in longer returns a.
Check your understanding
Why does fn longer(a: &str, b: &str) -> &str need a lifetime annotation when fn first_word(line: &str) -> &str does not?
Reveal the answer
- With two reference inputs, the compiler cannot tell which one the result borrows from
- Functions that compare lengths always need annotations
- The annotation keeps
aandbalive until the end ofmain - A
&strresult always needs'static
Elision covers one reference input, and &self methods. With two, you state the relationship; the annotation constrains callers and never extends a value's life.
Go deeper
Common misconception: “Adding 'a makes the references live longer.”
Lifetimes are checked, not executed. An annotation only describes which borrow the result depends on; if the data is dropped too early, the annotation makes the error precise rather than making the code valid.
- Name the source: For each returned reference, decide which input it points into; that input gets the output's lifetime.
- Leave the others free: Inputs the result never points into keep their own, elided lifetime.
- Test a short-lived input: Drop the unrelated input in an inner block and use the result afterwards; it must still compile.
Transfer challenge: Write struct Field<'a> { name: &'a str } and a function that tries to build one from a String that goes out of scope first; read where rustc reports the error.
Connections
- Pointer + Length to Slices: A view that carries its own bounds
- Struct Copies: Copy and Clone: Bitwise copies only for plain data

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: Dangling Pointers and Lifetimes (courseId "rust-for-c-developers", lessonId "c-dangling-pointers-to-lifetimes") Link: https://crabrix.com/learn/rust-for-c-developers/c-dangling-pointers-to-lifetimes/ Goal: A lifetime annotation relates the output borrow to the input borrows; it never extends how long any value lives. Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=rust-for-c-developers/c-dangling-pointers-to-lifetimes) 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.