এই বইটি এখনো বাংলা ভাষায় পাওয়া যায় না। সংস্করণ: English।
University Computer Science — Year 2 · স্নাতক দ্বিতীয় বর্ষ
6Rust: Ownership and Borrowing
Last year’s most frequent error, in five lines of C: a block is freed through one pointer and read through another. The compiler accepts it; only the sanitizer, at run time, on the input that reaches the line, notices.
char *name = malloc(16);
strcpy(name, "Mill Lane");
char *shown = name; /* a second pointer to the same block */
free(name); /* the owner gives the block back */
printf("%s\n", shown); /* ...and the other pointer still uses it */
$ gcc -std=c17 -O0 -g -fsanitize=address use_after_free.c -o use_after_free
$ ./use_after_free
=================================================================
==1000==ERROR: AddressSanitizer: heap-use-after-free on address 0x502000000010 at pc 0x7ffff7440c12 bp 0x7fffffffec80 sp 0x7fffffffe428
READ of size 2 at 0x502000000010 thread T0
#1 0x5555555552ff in main ~/session/use_after_free.c:13
The same program in Rust, the language of this part of the book:
fn main() {
let name = String::from("Mill Lane");
let shown = &name; // a reference to the same string
drop(name); // the owner gives the string back
println!("{shown}"); // ...and the reference still uses it
}
$ rustc --edition 2021 -O -o use_after_free use_after_free.rs && ./use_after_free
error[E0505]: cannot move out of `name` because it is borrowed
--> use_after_free.rs:6:10
|
4 | let name = String::from("Mill Lane");
| ---- binding `name` declared here
5 | let shown = &name; // a reference to the same string
| ----- borrow of `name` occurs here
6 | drop(name); // the owner gives the string back
| ^^^^ move out of `name` occurs here
7 | println!("{shown}"); // ...and the reference still uses it
| ----- borrow later used here
[exit status 1]
The compiler has found, without running anything, that the string is given back while a reference to it is still to be used, and it names the three lines involved. It did so by applying a few rules about who owns each value and who may use it when. This chapter states them; they forbid the use after free, the double free and, as Chapter 15 will show, the data race, in every program that compiles.
You already know
Book 3: a block of the heap is obtained with malloc and given back with free; using it afterwards (use after free) or freeing it twice (double free) is undefined behaviour, which the address sanitizer detects at run time. Chapters 1 and 2: in C++, an object that owns a resource frees it in its destructor (RAII), and a move transfers the resource, leaving the source empty but still usable.
6.1 Rust in a few pages
Rust is a compiled language, like C and C++: rustc file.rs produces an executable, with no garbage collector and no run-time system beyond C’s. Its syntax will look familiar.
fn fine_cents(days_late: u32) -> u32 {
// the last expression, with no semicolon, is the value returned
(10 * days_late).min(500)
}
fn main() {
let town = "Riverside"; // immutable by default; its type, &str, is inferred
let mut total: u32 = 0; // mut: this binding may change
let delays = vec![3, 0, 12, 75]; // a Vec<u32>, growable, on the heap
for d in &delays {
total += fine_cents(*d);
}
let average = total as f64 / delays.len() as f64; // no implicit conversions: `as`
println!("{town}: {} loans, {total} cents of fines, {average:.2} on average",
delays.len());
let big: u8 = 250;
println!("{:?} {:?} {}", big.checked_add(10), big.checked_add(5), big.wrapping_add(10));
}
$ rustc --edition 2021 -O -o hello hello.rs && ./hello
Riverside: 4 loans, 650 cents of fines, 162.50 on average
None Some(255) 4
A few points differ from C. let introduces a binding, immutable unless declared mut. Types are written after the name (total: u32) and are inferred where possible: u8 to u64 and i8 to i64 are the integers with their sizes in bits, usize the size of a pointer, f64 the double. There is no implicit conversion between numeric types: as converts. A block is an expression whose value is its last expression, written without a semicolon, which is how fine_cents returns. An arithmetic overflow stops the program in a debug build; checked_add returns None instead of overflowing and wrapping_add wraps modulo on purpose. println! is a macro, hence the !, whose {} are replaced by the arguments or by the variables named inside them. Tests live in a crate, Rust’s unit of compilation, managed by the tool cargo; the tests of this chapter form the crate tests/ownership. Rust 2021 is the edition of the language used throughout, the one that came with Rust 1.56 in October 2021.
6.2 Ownership
Definition 6.1 (Owner, ownership)
In Rust, every value has exactly one owner, the variable (or the field, or the element of a collection) that holds it. When the owner goes out of scope, the value is dropped. Ownership is this relation, and the rule that it is unique at every moment.
Definition 6.2 (Drop)
To drop a value is to run its clean-up code, its Drop implementation if it has one, then to drop its fields, and finally to free its memory. The compiler inserts the drops, at the end of the owner’s scope, in the reverse order of declaration; drop(x) drops x earlier.
A String is three words on the stack, a pointer, a length and a capacity, and a buffer on the heap, which it owns. Assigning it to another variable does not copy the buffer.
Definition 6.3 (Move)
A move transfers ownership of a value: an assignment let b = a;, the passing of a as an argument by value, or its return from a function copies the bytes of a’s stack part to the destination, which becomes the owner. The source is then moved from: the compiler refuses any later use of it, and does not drop it.
fn main() {
let a = String::from("Quay Street");
let b = a; // a move: b now owns the buffer; a can no longer be used
let c = b.clone(); // a second buffer, with the same bytes
println!("b = {b}, c = {c}");
println!("same buffer? {}", b.as_ptr() == c.as_ptr());
let x = 42; // an i32 is Copy: assignment copies the bits
let y = x;
println!("x = {x}, y = {y}"); // both usable
let moved_into = takes(c); // c moves into the function's parameter...
println!("{moved_into}"); // ...and the result moves back out
}
fn takes(s: String) -> usize {
s.len()
} // s is dropped here: its buffer is freed
$ rustc --edition 2021 -O -o move_string move_string.rs && ./move_string
b = Quay Street, c = Quay Street
same buffer? false
x = 42, y = 42
11
clone, two buffers.String. The three words of a are copied into b; the buffer stays where it is, with one owner, b. The compiler forbids any use of a afterwards and drops only b, so the buffer is freed exactly once. In C++, a move would also have emptied a, and run its destructor later; in Rust nothing runs on a at all.error[E0382]: borrow of moved value: `a`
--> use_after_move.rs:6:16
|
4 | let a = String::from("Quay Street");
| - move occurs because `a` has type `String`, which does not implement the `Copy` trait
5 | let b = a;
| - value moved here
6 | println!("{a} {b}");
| ^ value borrowed here after move
[exit status 1]
a after let b = a; is refused. Some lines are left out.Definition 6.4 (Copy type)
A copy type is a type whose values are duplicated by copying their bytes, with no resource to free, and that implements the Copy trait: the integers, f64, bool, char, shared references, and tuples and arrays of copy types. For a copy type, assignment and passing by value copy, and the source stays usable. A type that owns a resource, such as String or Vec, cannot be Copy.
A deliberate copy of a String is a clone: a new buffer with the same bytes. Clones are visible in the code, which is the point: a C++ copy runs silently at an initialisation or an assignment (copy constructor, copy assignment), a Rust clone is written.
6.3 Borrowing
Moving every value into every function that reads it would be impractical. A function can instead borrow it.
Definition 6.5 (Borrow)
A borrow is a reference to a value that does not take ownership of it. A shared borrow &x, of type &T, allows reading the value; a mutable, or exclusive, borrow &mut x, of type &mut T, allows changing it. The borrowing rule: at any point of the program, a value has either any number of shared borrows in use, or exactly one exclusive borrow in use, but not both; and no borrow is used after the value is moved or dropped.
A borrow is in use from its creation to its last use, not to the end of its block: the compiler follows the program’s paths, line by line.
fn letters(s: &str) -> usize {
// a shared borrow: may read, may not change
s.chars().filter(|c| c.is_alphabetic()).count()
}
fn add_suffix(s: &mut String, suffix: &str) {
// an exclusive borrow: the only access while it lasts
s.push(' ');
s.push_str(suffix);
}
fn main() {
let mut street = String::from("Mill");
let r1 = &street;
let r2 = &street; // any number of shared borrows at once
println!("{} {} letters", r1, letters(r2));
add_suffix(&mut street, "Lane"); // r1 and r2 are no longer used: allowed
println!("{street}: {} letters", letters(&street));
let m = &mut street;
m.make_ascii_uppercase();
println!("{street}"); // m's last use was the line before
}
$ rustc --edition 2021 -O -o borrow_rules borrow_rules.rs && ./borrow_rules
Mill 4 letters
Mill Lane: 8 letters
MILL LANE
error[E0499]: cannot borrow `street` as mutable more than once at a time
--> two_mut.rs:6:18
|
5 | let first = &mut street;
| ----------- first mutable borrow occurs here
6 | let second = &mut street;
| ^^^^^^^^^^^ second mutable borrow occurs here
7 | first.push_str(" Lane");
| ----- first borrow later used here
two_mut.rs). Some lines are left out.Definition 6.6 (Borrow checker)
The borrow checker is the part of the Rust compiler that checks, for every function, that each value is used only while owned and not moved, and that the borrowing rule holds at every point, using the types of the function’s parameters and results and not the bodies of the functions it calls.
The rule is what makes the use after free of the opening impossible: dropping name needs to move it, a move is a use incompatible with any borrow in use, and shown was in use until the println!. It also excludes a whole family of errors that are not about freeing.
Proposition 6.7 (Aliasing excludes mutation)
In a program accepted by the borrow checker, with no unsafe code, if at some point a value is changed through a path (its owner, or an exclusive borrow), then no other path to that value is in use at that point. In particular, outside the types built for shared mutation (Cell, the atomics, Mutex, all built on UnsafeCell; Chapter 15), two accesses to one value, one of which is a write, can never be in use at the same time: in one thread, a value does not change behind a reader; across threads, there is no data race. Those types change a value through shared references, and still exclude data races.
Proof. A write goes through the owner, which requires that no borrow be in use, or through an exclusive borrow, which by the borrowing rule is the only borrow in use; and while an exclusive borrow is in use, the owner itself cannot be used, since using it would end or contradict the borrow. A second access in use at the same point would be a second borrow, or a use of the owner, against the rule. Threads receive values only by move or by borrow, so the same counting applies across them. This argument assumes that the compiler applies the rules correctly to the whole language and that the library code written with unsafe respects them. That the rules indeed make the language safe was proved formally for a realistic subset of Rust in 2018, in a machine-checked proof that also covers several library types; we admit it. ∎
let mut count = 0;
thread::scope(|s| {
s.spawn(|| count += 1);
s.spawn(|| count += 1);
});
println!("{count}");
error[E0499]: cannot borrow `count` as mutable more than once at a time
--> race.rs:9:17
|
7 | thread::scope(|s| {
| - has type `&'1 Scope<'1, '_>`
8 | s.spawn(|| count += 1);
| ----------------------
| | | |
| | | first borrow occurs due to use of `count` in closure
| | first mutable borrow occurs here
| argument requires that `count` is borrowed for `'1`
9 | s.spawn(|| count += 1);
| ^^ ----- second borrow occurs due to use of `count` in closure
| |
| second mutable borrow occurs here
Each closure, || count += 1, changes count, so it holds an exclusive borrow of it; the two threads may run at the same time, so both borrows are in use at once. Chapter 15 shows the types that make such a counter possible: an atomic integer, a mutex.
Method 6.8 (Fixing a borrow error)
When the borrow checker refuses a program, read the three places the message names: where the borrow starts, the conflicting use, and where the borrow is used later. Then, in order of preference:
- shorten the first borrow: finish using it before the conflicting use, for instance by copying out the small value it was needed for (a length, an index);
- split the borrow: borrow two disjoint parts of the value instead of the whole, two fields, or two halves of a slice with
split_at_mut; - clone, if the value is small or the copy is needed anyway, and count what it costs;
- restructure: change who owns what, for instance return an owned value instead of a reference, or keep indices instead of references.
6.4 Lifetimes
Definition 6.9 (Dangling reference)
A dangling reference is a reference used after the value it refers to was dropped, or moved: what C calls a dangling pointer, and what the use after free of the opening read.
Definition 6.10 (Lifetime of a reference)
The lifetime of a reference, written 'a, is the region of the program in which the reference may be used. It must lie within the lifetime of the object referred to, the span from its creation to its drop or move (the lifetime of an object in Book 3’s sense). A function whose result is a reference names, by lifetime parameters in its signature, the arguments the result may borrow from.
A function that returns a reference must borrow it from one of its arguments: a reference to one of its own locals would dangle as soon as it returns.
error[E0106]: missing lifetime specifier
--> dangling.rs:3:24
|
3 | fn default_street() -> &String {
| ^ expected named lifetime parameter
|
= help: this function's return type contains a borrowed value, but there is no value for it to be borrowed from
help: instead, you are more likely to want to return an owned value
|
3 - fn default_street() -> &String {
3 + fn default_street() -> String {
dangling.rs). Some lines are left out.When a function takes two references and returns one of them, the compiler cannot guess which; the signature says it.
pub fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
// the result lives as long as the shorter-lived of x and y
if x.len() >= y.len() {
x
} else {
y
}
}
pub fn first_letter(s: &str) -> &str {
// elided: one input reference, so the output borrows from it
match s.char_indices().nth(1) {
Some((i, _)) => &s[..i],
None => s,
}
}
#[allow(dead_code)]
fn main() {
let a = String::from("Orchard Way");
let result;
{
let b = String::from("Mill Row");
println!("{}", longest(&a, &b)); // used while both live: fine
result = first_letter(&a);
}
println!("{result}"); // borrows only from a, which still lives
}
$ rustc --edition 2021 -O -o longest longest.rs && ./longest
Orchard Way
O
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str reads: for some region 'a in which both arguments are valid, the result is valid in 'a. A caller may therefore use the result only while both arguments live. first_letter needs no annotation: by the elision rules, a function with exactly one reference parameter returns a reference borrowed from it, and a method with &self returns one borrowed from self. The caller checks only the signature, never the body: longest_scope.rs keeps the result of longest after b is dropped, and is refused even though, with these strings, longest returns a.
error[E0597]: `b` does not live long enough
--> longest_scope.rs:12:30
|
11 | let b = String::from("Mill Row");
| - binding `b` declared here
12 | result = longest(&a, &b);
| ^^ borrowed value does not live long enough
13 | }
| - `b` dropped here while still borrowed
14 | println!("{result}");
| ------ borrow later used here
longest_scope.rs, as vertical bars over its source lines. The result must be valid at the println!, line 7, but it may borrow from b, which is dropped at the end of line 6: no region 'a lies within both, and the program is refused.6.5 Slices and strings
Definition 6.11 (Slice, string slice)
A slice &[T] is a borrowed view of a contiguous run of values of type T, inside an array, a vector or another slice: a pointer to its first element and a number of elements. A string slice &str is a borrowed view of a run of bytes that is valid UTF-8; a String owns such bytes and can grow, a &str only borrows them. &v[i..j] is the slice of the elements from i up to, but not including, j.
pub fn total(pages: &[u32]) -> u32 {
// any contiguous run of u32: an array, a Vec, or a part of one
pages.iter().sum()
}
#[allow(dead_code)]
fn main() {
let pages = [65, 133, 412, 98, 251];
let middle = &pages[1..4]; // elements 1, 2 and 3: a pointer and a length
println!("{:?} {} {}", middle, total(middle), total(&pages));
let v = vec![10, 20, 30];
println!("{}", total(&v)); // a &Vec<u32> becomes a &[u32]
let street = String::from("Café Lane"); // é takes two bytes in UTF-8
let first: &str = &street[0..5]; // bytes 0 to 4: a string slice
println!("{first:?}, {} bytes, {} chars", street.len(), street.chars().count());
let literal: &str = "Mill Row"; // a literal is a &str into the program's data
println!("{}", &literal[5..]);
}
$ rustc --edition 2021 -O -o slices slices.rs && ./slices
[133, 412, 98] 643 959
60
"Café", 10 bytes, 9 chars
Row
u32.middle of Listing 6.8: two words, a pointer to element 1 and the length 3, and no copy of the elements. While it is in use, pages is borrowed: it cannot be changed or dropped.A &str is a slice of bytes, but its bounds are byte indices, and UTF-8 encodes é in two bytes: in the string Café Lane, the bytes 3 and 4 are one character. A slice that would cut a character in two is not a string, and the index operation refuses it, at run time when the index is only known then.
let street = String::from("Café Lane");
let n: usize = std::env::args().count() + 3; // 4, from a value only known at run time
println!("first {n} bytes: {}", &street[0..n]);
$ rustc --edition 2021 -O -o char_boundary char_boundary.rs && ./char_boundary
panicked at char_boundary.rs:10:44:
end byte index 4 is not a char boundary; it is inside 'é' (bytes 3..5 of string)
[exit status 101]
A panic, defined in Chapter 7, stops the program in an orderly way: it is a bug reported, not memory corrupted. The safe ways to cut a string, s.get(0..n), which returns None, or char_indices, are the subject of Chapter 7.
In practice — Owned or borrowed?
Take parameters as &str and &[T] rather than &String and &Vec<T>: every string and every vector can be borrowed as a slice, and the function serves them all. Return owned values (String, Vec<T>) when the function creates them, and references only when the result is a part of an argument. Store owned values in structures, unless the structure is clearly a short-lived view of other data.
6.6 Exercises
Exercise 6.1 ★
For each of the five snippets a to e, say whether it compiles, and if not which rule it breaks. Then check with the session in the solution, which builds each one in turn.
#[cfg(a)]
fn snippet() {
let s = String::from("Mill");
let t = &s;
let u = &s;
println!("{t} {u}");
}
#[cfg(b)]
fn snippet() {
let mut v = vec![1, 2, 3];
let first = &v[0];
v.push(4);
println!("{first}");
}
#[cfg(c)]
fn snippet() {
let n = 5;
let m = n;
println!("{n} {m}");
}
#[cfg(d)]
fn snippet() {
let s = String::from("Mill");
fn calc(s: String) -> usize { s.len() }
let len = calc(s);
println!("{s} has {len} bytes");
}
#[cfg(e)]
fn snippet() {
let mut s = String::from("Mill");
let r = &mut s;
r.push_str(" Row");
let t = &s;
println!("{t}");
}
Solution
Solution of Exercise 6.1.
$ for s in a b c d e; do echo "$s: $(rustc --edition 2021 --cfg $s exo_compile.rs 2>&1 | grep -m1 '^error\[' || echo compiles)"; done
a: compiles
b: error[E0502]: cannot borrow `v` as mutable because it is also borrowed as immutable
c: compiles
d: error[E0382]: borrow of moved value: `s`
e: compiles
a: two shared borrows in use together, allowed. b: first borrows v, push needs an exclusive borrow while first is still to be printed: refused (and rightly: the push may reallocate). c: i32 is a copy type, so n stays usable. d: s moved into calc, then used: refused. e: the exclusive borrow r is last used on the line before t is created, so the two are never in use together: allowed.
Exercise 6.2 ★
Explain the error with Definition 6.5, then fix the program in two ways from Method 6.8.
fn main() {
let mut names = vec![String::from("Mill Row"), String::from("Quay Street")];
let shortest = names.iter().min_by_key(|n| n.len()).unwrap();
names.push(String::from("Bridge Way"));
println!("shortest: {shortest}, {} names", names.len());
}
error[E0502]: cannot borrow `names` as mutable because it is also borrowed as immutable
--> exo_e0502.rs:6:5
|
5 | let shortest = names.iter().min_by_key(|n| n.len()).unwrap();
| ----- immutable borrow occurs here
6 | names.push(String::from("Bridge Way"));
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
7 | println!("shortest: {shortest}, {} names", names.len());
| -------- immutable borrow later used here
Solution
Solution of Exercise 6.2.
shortest is a shared borrow of an element of names, in use until the println!; push needs an exclusive borrow of names in between. The push may reallocate the vector’s buffer, and shortest would dangle. Fix 1, shorten: push before computing shortest, or print first and push after. Fix 2, clone: let shortest = names.iter().min_by_key(|n| n.len()).unwrap().clone();, an owned copy of one short string. A third, restructure: keep the index of the shortest name and read names[i] after the push.
Exercise 6.3 ★
Write fn first_word(s: &str) -> &str, which returns the part of s before its first whitespace character, or all of s. Why does its signature need no lifetime annotation? Why can the slice it returns never cut a character in two? Test it on a word containing é.
Solution
Solution of Exercise 6.3.
pub fn first_word(s: &str) -> &str {
// up to the first whitespace character, or the whole string
match s.find(char::is_whitespace) {
Some(i) => &s[..i], // i is the byte index of a character: always a boundary
None => s,
}
}
One reference parameter: by the elision rules the result borrows from s. find returns the byte index at which a character begins (here the whitespace), so &s[..i] ends on a boundary. The tests cover Café, a tab, a single word and a leading space, which gives the empty string.
Exercise 6.4 ★
How many heap allocations does main make below, and how many times is a buffer enlarged? Count line by line before reading the output in the solution: an empty Vec allocates nothing, and the first push allocates room for four Strings.
fn main() {
let before = ALLOCS.load(Relaxed);
let a = String::from("Mill");
let b = a.clone();
let mut v: Vec<String> = Vec::new();
v.push(b);
v.push(a.clone());
let c = v[0].clone() + " Lane";
let d = &c;
let e = d.to_uppercase();
let total = ALLOCS.load(Relaxed) - before;
println!("{total} allocations, {} reallocations ({a} {c} {e} {})",
REALLOCS.load(Relaxed), v.len());
}
Solution
Solution of Exercise 6.4.
$ rustc --edition 2021 -O -o exo_clones exo_clones.rs && ./exo_clones
6 allocations, 1 reallocations (Mill Mill Lane MILL LANE 2)
String::from 1, a.clone() 2, Vec::new() none, the first push 3 (room for four), a.clone() 4, v[0].clone() 5; + " Lane" appends to that clone, whose buffer of exactly 4 bytes is enlarged: the reallocation. &c allocates nothing; to_uppercase builds a new string: 6. Moves (v.push(b), the result of +) allocate nothing.
Exercise 6.5 ★★
Noisy prints its name when it is dropped. Predict the ten lines the program prints, with Definition 6.2, then check them in the solution. Explain the lines drop c and drop a2.
struct Noisy(&'static str);
impl Drop for Noisy {
fn drop(&mut self) {
println!("drop {}", self.0);
}
}
fn consume(n: Noisy) {
println!("consume {}", n.0);
}
fn main() {
let _a = Noisy("a");
let b = Noisy("b");
let _ = Noisy("c");
let v = vec![Noisy("d"), Noisy("e")];
consume(b);
{
let _f = Noisy("f");
println!("end of block");
}
let _a = Noisy("a2"); // shadows _a, which still lives
drop(v);
println!("end of main");
}
Solution
Solution of Exercise 6.5.
$ rustc --edition 2021 -O -o exo_drop exo_drop.rs && ./exo_drop
drop c
consume b
drop b
end of block
drop f
drop d
drop e
end of main
drop a2
drop a
let _ = Noisy("c"); binds nothing: the pattern _ does not take ownership, so the temporary is dropped at the end of the statement, first of all. b moves into consume and is dropped at the end of that function. f at the end of its block. drop(v) drops the vector, whose elements are dropped in order, d then e. The second _a shadows the first without dropping it (a name starting with _ still owns); at the end of main the locals are dropped in reverse order of declaration: a2, then a.
Exercise 6.6 ★★
This function returns a reference to its own local. Explain the error, and give the fix the compiler suggests in Output 6.9. What would the equivalent C function return, and when would the bug show?
fn joined(names: &[String]) -> &str {
let line = names.join(", ");
&line
}
error[E0515]: cannot return reference to local variable `line`
--> exo_return_local.rs:5:5
|
5 | &line
| ^^^^^ returns a reference to data owned by the current function
Solution
Solution of Exercise 6.6.
line is a String owned by joined and dropped when it returns; &line would point to a freed buffer. The fix: return the owned value, fn joined(names: &[String]) -> String, with line as the last expression; the buffer moves to the caller. The C version, returning a char * to a malloced buffer that it freed, or to a local array, compiles; the caller reads freed memory or a dead stack frame, which usually still holds the right bytes until the next call overwrites them, so the bug shows later and elsewhere.
Exercise 6.7 ★★
let (l, r) = (&mut v[..m], &mut v[m..]); is refused: two exclusive borrows of v. Write add_halves, which adds each element of the first half of a mutable slice to the matching element of the second half, with split_at_mut. Why may the library give two exclusive borrows here, when the compiler would not? Then write largest_first, which swaps the largest element to the front, with split_first_mut.
Solution
Solution of Exercise 6.7.
/// Adds each element of the first half to the matching element of the second half.
pub fn add_halves(v: &mut [i32]) {
let mid = v.len() / 2;
let (left, right) = v.split_at_mut(mid); // two &mut [i32] that cannot overlap
for (r, l) in right.iter_mut().zip(left.iter()) {
*r += *l;
}
}
/// The largest element moved to the front, by swapping it with the first.
pub fn largest_first(v: &mut [i32]) {
if let Some((first, rest)) = v.split_first_mut() {
if let Some(big) = rest.iter_mut().max_by_key(|x| **x) {
if *big > *first {
std::mem::swap(first, big);
}
}
}
}
The borrow checker reasons on whole values: &mut v[..m] borrows v, and so does &mut v[m..], whatever the ranges. split_at_mut is a library function whose body uses unsafe code to build the two slices from one pointer; its signature returns two &mut [T] that borrow v, and the library guarantees, by construction, that they do not overlap. tests/ownership checks both functions, including an odd length, equal largest elements and an empty slice.
Exercise 6.8 ★★
Explain why fn f<'a>(x: &'a str, y: &str) -> &'a str may return x but not y. What does the signature promise the caller, and which call would become unsafe if y could be returned? Rewrite the signature so that either may be returned, and say what the caller loses.
Solution
Solution of Exercise 6.8.
The signature promises that the result is valid wherever x is, and says nothing of y, whose lifetime is unrelated. A caller may thus keep the result after y is dropped: let r; { let t = String::from("tmp"); r = f(&a, &t); } println!("{r}"); compiles. If f returned y, r would dangle; the compiler refuses the body instead. Giving both the same lifetime, fn f<'a>(x: &'a str, y: &'a str) -> &'a str, allows returning either; the caller loses the call above, which is then refused because t does not live long enough.
Exercise 6.9 ★★
Write fn reverse_words(s: String) -> String, which reverses the order of the words (separated by single spaces) in the string’s own buffer, with no new allocation: reverse all the bytes, then each word. Prove that the result is valid UTF-8 even when the words contain multi-byte characters, and test that the returned buffer is the original one.
Solution
Solution of Exercise 6.9.
pub fn reverse_words(s: String) -> String {
let mut b = s.into_bytes(); // the same buffer, now seen as bytes: no copy
b.reverse(); // the whole text backwards: words in the right order, each one backwards
for word in b.split_mut(|&c| c == b' ') {
word.reverse(); // each word forwards again, its multi-byte characters too
}
// every character's bytes were reversed exactly twice: the bytes are valid UTF-8 again
String::from_utf8(b).expect("reversed twice, so valid")
}
Let the text be , words separated by spaces. Reversing all bytes gives , each word’s bytes in reverse order; reversing each word gives back . Each multi-byte character lies inside one word, so its bytes are reversed twice and recover their order; spaces are single bytes. The final bytes are therefore the concatenation of valid encoded characters, valid UTF-8, and from_utf8 succeeds without copying. into_bytes and from_utf8 reuse the buffer: the test compares the addresses.
Exercise 6.10 ★★★
Write a generic stack Stack<T> as a chain of nodes, each a Box<Node<T>> owning the next node, with push, pop, peek and peek_mut. Why does push need Option::take? Show that the default drop of a chain of a million nodes is a recursion a million calls deep, and write a Drop that frees it with a loop. Test the stack against a Vec.
Solution
Solution of Exercise 6.10.
// stack.rs: a stack as a chain of boxed nodes (exercise 10).
struct Node<T> {
value: T,
next: Option<Box<Node<T>>>, // the node owns the rest of the chain
}
pub struct Stack<T> {
head: Option<Box<Node<T>>>,
len: usize,
}
impl<T> Default for Stack<T> {
fn default() -> Self {
Stack { head: None, len: 0 }
}
}
impl<T> Stack<T> {
pub fn push(&mut self, value: T) {
let next = self.head.take(); // move the old chain out, leaving None
self.head = Some(Box::new(Node { value, next }));
self.len += 1;
}
pub fn pop(&mut self) -> Option<T> {
let node = self.head.take()?; // we now own the top node
self.head = node.next;
self.len -= 1;
Some(node.value)
}
impl<T> Drop for Stack<T> {
fn drop(&mut self) {
// a loop, not the default recursion: a long chain would overflow the call stack
let mut cur = self.head.take();
while let Some(mut node) = cur {
cur = node.next.take();
}
}
}
self.head cannot be moved out of a borrowed self, since self would be left without a head; take moves the value out and puts None in its place, a legal exclusive use of the field. The default drop of a Box<Node> drops its next field, which drops the next box, and so on: one nested call per node, and a million nested calls overflow the 8 MB stack of the main thread. The Drop above detaches each node before dropping it, so each node is dropped with no successor. The test pushes a million values and drops the stack, and compares 10 000 random operations with a Vec.
Exercise 6.11 ★★★
The loop of Listing 5.4 read freed memory after a push_back. (a) Prove, with Definition 6.5, that no Rust program without unsafe can push onto a vector while a loop iterates over it. (b) Check your argument against the compiler’s message for the same loop in Rust, in the solution. (c) Write the loop the way Rust accepts, and compare it with the fixes of the C++ chapter.
Solution
Solution of Exercise 6.11.
(a) A loop over a vector holds an iterator, which is a shared borrow of the vector (or an exclusive one, for iter_mut), in use from the start of the loop to its last iteration. push takes &mut self, an exclusive borrow; a call inside the body would make it in use together with the iterator’s borrow, which the borrowing rule forbids. Without unsafe, there is no other path to the vector. (b)
error[E0502]: cannot borrow `due` as mutable because it is also borrowed as immutable
--> invalidation.rs:8:13
|
5 | for d in &due {
| ----
| |
| immutable borrow occurs here
| immutable borrow later used here
...
8 | due.push(d + 21);
| ^^^^^^^^^^^^^^^^ mutable borrow occurs here
The message names exactly the two borrows. (c) Collect the renewals in a new vector, with iter, filter and map and a final collect, then append them after the loop with due.extend. That was the first fix of the C++ chapter; it is now the one the compiler accepts. The index loop works too, since due[i] borrows only for the duration of the expression.
Exercise 6.12 ★★★
To satisfy the borrow checker, a port of a C program wrote distinct as below. The output counts the heap allocations for names, each appearing twice. Find the hidden cost, count the allocations exactly as a function of , and fix the function with no clone of seen; then give a version in expected time.
fn distinct(names: &[String]) -> Vec<String> {
let mut seen: Vec<String> = Vec::new();
for n in names {
let known = seen.clone(); // "cannot borrow `seen`": cloned to make it compile
if !known.contains(n) {
seen.push(n.clone());
}
}
seen
}
$ rustc --edition 2021 -O -o exo_quadratic exo_quadratic.rs && ./exo_quadratic
n = 100: 50 distinct, 3879 allocations
n = 200: 100 distinct, 15255 allocations
n = 400: 200 distinct, 60506 allocations
Solution
Solution of Exercise 6.12.
seen.clone() copies the vector and every string in it, at every step. With names, the first distinct, step clones strings, which costs allocations when (the strings and the vector’s buffer). Adding the clones pushed and the buffers of seen, the total is : 3879, 15 255 and 60 506 for , 200 and 400, the printed values, and . The clone was never needed: seen.contains(n) borrows seen only for the call, so seen.push after it is legal.
pub fn distinct(names: &[String]) -> Vec<String> {
let mut seen: Vec<String> = Vec::new();
for n in names {
if !seen.contains(n) {
// the shared borrow of `contains` ended with the call
seen.push(n.clone());
}
}
seen
}
pub fn distinct_fast(names: &[String]) -> Vec<String> {
let mut known: HashSet<&str> = HashSet::new(); // borrows the names: no copy to test
names.iter().filter(|n| known.insert(n.as_str())).cloned().collect()
}
distinct still compares each name with the list, comparisons but only allocations; distinct_fast keeps borrowed &strs in a hash set and is expected. The test checks that both give the same names in the order of first appearance.
6.7 Problem: Porting the dictionary that crashed
Problem 6.1
Weekend problem — Porting the dictionary that crashed
A word counter in C, a hash table with open addressing in dict.h, worked for years, then crashed three times, in three versions, each time after an innocent-looking change. This problem finds the three errors, ports the counter to Rust, and measures what the port costs.
Part I — Three memory errors in C.
The function dict_count(d, word) returns a pointer to the counter of word, creating it at 0; an insertion may grow the table, which moves every slot to a new block and frees the old one. Each version below is built with -DBUG=1, 2 or 3, and run on the titles of the town’s books.
struct dict d;
dict_init(&d, 8);
char *line = NULL;
size_t size = 0;
while (getline(&line, &size, stdin) != -1) /* one buffer, reused for every line */
for (char *w = strtok(line, " ,\n"); w; w = strtok(NULL, " ,\n")) {
#if BUG == 1
int *first = dict_count(&d, "The"); /* BUG 1: a pointer kept across insertions */
(*dict_count(&d, w))++;
(*first) += 0;
#else
(*dict_count(&d, w))++;
#endif
}
free(line);
const char *best = NULL; /* borrowed from the table */
int most = 0;
for (size_t i = 0; i < d.cap; i++)
if (d.slots[i].word && d.slots[i].count > most) {
best = d.slots[i].word;
most = d.slots[i].count;
}
printf("%zu different words; most frequent: %s (%d)\n", d.len, best, most);
#if BUG == 2
free((char *)best); /* BUG 2: the caller frees a word the table owns */
#endif
dict_free(&d);
return 0;
dict.c: the main program and its three versions code/bachelor-2/06-rust-ownership/listings/dict.c$ gcc -std=c17 -O0 -g -fsanitize=address dict.c -o dict && ./dict < titles.txt
34 different words; most frequent: The (42)
$ gcc -std=c17 -O0 -g -fsanitize=address -DBUG=1 dict.c -o dict1 && ./dict1 < titles.txt
==1000==ERROR: AddressSanitizer: heap-use-after-free on address 0x50c000000088 at pc 0x55555555611f bp 0x7fffffffeb90 sp 0x7fffffffeb80
READ of size 4 at 0x50c000000088 thread T0
#0 0x55555555611e in main ~/session/dict.c:18
freed by thread T0 here:
#0 0x7ffff74b4537 in __interceptor_free ../../../../src/libsanitizer/asan/asan_malloc_linux.cpp:127
#1 0x55555555594e in grow ~/session/dict.h:36
#2 0x555555555ced in dict_count ~/session/dict.h:54
#3 0x5555555560a6 in main ~/session/dict.c:17
$ gcc -std=c17 -O0 -g -fsanitize=address -DBUG=2 dict.c -o dict2 && ./dict2 < titles.txt
34 different words; most frequent: The (42)
=================================================================
==1000==ERROR: AddressSanitizer: attempting double-free on 0x502000000010 in thread T0:
#1 0x555555555e58 in dict_free ~/session/dict.h:73
#2 0x555555556369 in main ~/session/dict.c:35
freed by thread T0 here:
#0 0x7ffff74b4537 in __interceptor_free ../../../../src/libsanitizer/asan/asan_malloc_linux.cpp:127
#1 0x55555555635d in main ~/session/dict.c:33
$ gcc -std=c17 -O0 -g -fsanitize=address -DBUG=3 dict.c -o dict3 && ./dict3 < titles.txt
==1000==ERROR: AddressSanitizer: heap-use-after-free on address 0x50c000000100 at pc 0x7ffff745df89 bp 0x7fffffffea60 sp 0x7fffffffe1d8
READ of size 2 at 0x50c000000100 thread T0
#3 0x5555555562bb in main ~/session/dict.c:31
freed by thread T0 here:
#0 0x7ffff74b4537 in __interceptor_free ../../../../src/libsanitizer/asan/asan_malloc_linux.cpp:127
#1 0x5555555560d4 in main ~/session/dict.c:23
- Without bugs, the program prints 34 words; the previous chapter counted 33 in the same titles. Why?
- Version 1: which pointer is read after its block was freed, and by which call was the block freed?
- Why does version 1 not crash on every input? Give an input on which it would read nothing freed.
- Version 2: who owns the string
bestpoints to? Explain the double free. - Version 3:
dict_countkeeps the caller’s pointer instead of a copy. Into which buffer does it point, and why are some counts already wrong before the crash? - Without the sanitizer, what might each version print? Which of the three is the most dangerous?
Part II — An ownership design in Rust.
/// The counter of `word`, created at 0 if missing; the table stays borrowed while used.
pub fn count(&mut self, word: &str) -> &mut u32 {
let mut i = self.find(word);
if self.slots[i].is_none() {
if 2 * (self.len + 1) > self.slots.len() {
self.grow();
i = self.find(word);
}
self.slots[i] = Some((word.to_string(), 0)); // the table's own copy
self.len += 1;
}
&mut self.slots[i].as_mut().unwrap().1
}
Dict::count, from dict_table.rs code/bachelor-2/06-rust-ownership/listings/dict_table.rs- The slots are
Vec<Option<(String, u32)>>. Who owns each word, and who frees it, and when? growreplaces the vector withstd::mem::replace, then moves each pair into the new one. Why is no word copied, and why couldgrownot simply readself.slotswhile filling a new vector stored inself.slots?countreturns&mut u32. What does its elided lifetime say?- Why is there no
dict_freein Rust, and what plays its role? dict.rsreads each line into a freshString. Why can the words of the line be passed tocountas&stralthough the line is dropped at the end of each iteration?- Write the order in which the memory of a
Dictholding 34 words is freed at the end ofmain.
Part III — The three errors, refused.
dict_bugs.rs writes each bug in Rust; the session builds it three times.
$ rustc --edition 2021 -O dict.rs -o dict && ./dict < titles.txt
34 different words; most frequent: The (42)
$ for b in bug1 bug2 bug3; do rustc --edition 2021 --cfg $b dict_bugs.rs 2>&1 | grep -m1 -A9 '^error\['; done
error[E0499]: cannot borrow `*d` as mutable more than once at a time
--> dict_bugs.rs:11:6
|
10 | let first = d.count("The"); // a reference into the table, kept...
| - first mutable borrow occurs here
11 | *d.count(w) += 1; // ...across an insertion that may move the slots
| ^ second mutable borrow occurs here
12 | *first += 0;
| ----------- first borrow later used here
error[E0507]: cannot move out of `*best` which is behind a shared reference
--> dict_bugs.rs:18:24
|
18 | let mine: String = *best; // take the word for ourselves, to free it
| ^^^^^ move occurs because `*best` has type `String`, which does not implement the `Copy` trait
error[E0597]: `line` does not live long enough
--> dict_bugs.rs:27:18
|
26 | let line = format!("line {i}"); // a buffer that dies at the end of each iteration
| ---- binding `line` declared here
27 | for w in line.split(' ') {
| ^^^^ borrowed value does not live long enough
...
30 | }
| - `line` dropped here while still borrowed
- Error E0499: relate it to version 1, and to the rule the pointer is valid until the next insertion written in
dict.h’s comment. - Error E0507: relate it to version 2. Who may free a
String? - Error E0597: relate it to version 3, where a
HashMap<&str, u32>keeps borrowed words. - For each of the three, give the fix: the Rust code that does what the programmer meant.
- Which of the three would also be caught by C++ with
std::stringandstd::unordered_map, and which not? - The C comment documented the rule of version 1, and the bug happened anyway. What does the Rust signature of
countdo that the comment did not?
Part IV — The two versions measured.
The same 4 million words, drawn from 100 000 by the same generator, are counted by dict.h and by dict_table.rs, three times each, on the author’s laptop.
$ gcc -std=c17 -O2 dict_bench.c -o bench_c
$ rustc --edition 2021 -C opt-level=2 dict_bench.rs -o bench_rs
$ for i in 1 2 3; do ./bench_c; ./bench_rs; done
C: 100000 different, w7 32 times, 308 ms
Rust: 100000 different, w7 32 times, 327 ms
C: 100000 different, w7 32 times, 337 ms
Rust: 100000 different, w7 32 times, 330 ms
C: 100000 different, w7 32 times, 385 ms
Rust: 100000 different, w7 32 times, 336 ms
- Check that the two programs computed the same thing.
- Compute the mean time of each, and the spread between the runs of one program. Is the difference between the means larger than the spread?
- Rust checks the index of every
self.slots[i]. Why does this cost little here? - The Rust version makes one heap allocation per new word, the C version one
strdup. Where else could the two differ in cost? - What would a fair comparison need that these runs do not have?
- State the result of the problem: the three memory errors and what happened to them, and the measured speed of the two versions.
Solution
Solution of Problem 6.1.
1. This counter is case-sensitive: The and the are two words. The previous chapter lowered every word first.
2. first, the pointer to the counter of The, at line 18. The block was freed by grow, called by dict_count at line 17 when inserting a new word into a half-full table.
3. It reads freed memory only if an insertion grew the table between line 16 and line 18. An input whose distinct words never reach half the capacity, say one line The The, never grows the table of 8 slots.
4. The table: dict_count stored a strdup copy, and dict_free frees it. best only borrows it. main frees it, then dict_free frees it again.
5. Into line, the buffer of getline, which is overwritten by every new line and freed after the loop. Every stored word points into that one buffer, so after the next line is read the old words have changed: the comparisons of later lookups compare with the wrong text, and counts go to the wrong words.
6. Version 1 increments, or here only reads, a freed slot that malloc may have given to another use: silent corruption. Version 2 corrupts the allocator’s own lists, a crash later or an exploitable state. Version 3 prints wrong counts, or garbage, with no crash at all. Version 3 is the most dangerous: it is wrong on every input and may look plausible.
7. Each String is owned by its slot, the slots by the vector, the vector by the Dict. When the Dict is dropped, the vector drops each Option, which drops each String, freeing its buffer, then the vector frees its own buffer.
8. mem::replace moves the old vector out of self.slots, leaving the new empty one, so the function now owns the old one; into_iter moves each pair out of it, and moving a String copies its three words, not its bytes. Reading self.slots while writing a new vector stored in self.slots would need two borrows of the same field, one exclusive; after the replace they are two different vectors.
9. The result borrows from self (a method with &mut self): the Dict stays exclusively borrowed for as long as the returned counter is used.
10. The Dict is dropped automatically at the end of main, and the drop of its fields frees everything: the compiler wrote dict_free.
11. count copies the word (to_string) when it creates a slot, and only compares it otherwise; the borrow &str is needed only during the call, which ends before the line is dropped.
12. The 34 String buffers, one by one in the order of the slots, then the slots’ buffer; the three words of d on the stack disappear with the frame of main.
13. first is an exclusive borrow of d, in use until line 12; the second count needs another. The comment’s rule, valid until the next insertion, is exactly this borrow: the Rust signature makes it a rule the compiler checks.
14. Only the owner frees: a String is freed when its owner drops it. Through &String nothing can take ownership, so nothing can free it: E0507.
15. The map stores &str borrowed from line, which is dropped at the end of each iteration while the map lives on: E0597, the lifetime of the borrow exceeds that of the owner.
16. 1: finish with first before inserting, or call count("The") again when needed. 2: clone the word if an owned copy is needed: let mine = best.clone();. 3: store owned words, HashMap<String, u32>, inserting w.to_string() when a word is new, as Dict does.
17. Version 3 disappears with std::string keys, which own copies. Versions 1 and 2 remain: a pointer or reference into an unordered_map is stable across rehashes (the nodes do not move), so version 1 would even be correct there, but with a vector of slots it reads freed memory; and delete on a pointer obtained from c_str() compiles. C++ checks neither.
18. The comment states a rule for humans; the signature fn count(&mut self, word: &str) -> &mut u32 states the same rule in a form the compiler enforces at every call.
19. Both print 100 000 different words and the same count for w7: same generator, same counts.
20. On the printed run, both means are about a third of a second and lie within 5 % of each other, while the three runs of one program differ by up to about 25 %: the difference between the means is smaller than the spread.
21. The index is masked with cap - 1, and the check is one comparison with the length, predicted correctly every time; the probing loop is dominated by hashing, string comparison and cache misses.
22. Formatting the word (snprintf against write!), the hash written as a fold, strcmp against a slice comparison that first compares lengths, and the allocators’ handling of 100 000 small blocks.
23. Many runs on a quiet machine, the order of the runs alternated, the median and its spread reported, and both programs compiled by the same back end (gcc and rustc optimise differently).
24. Three memory errors refused at compile time, same speed within a measured margin: the use after free across an insertion (E0499), the double free of a borrowed word (E0507) and the words borrowed from a dead buffer (E0597) are all compile-time errors in Rust; and on the laptop the two versions run within 5 % of each other, inside the run-to-run spread.