Answer#
Safe Rust (code outside unsafe blocks) rules out a defined list of memory and concurrency bugs. Everything outside that list is still your job, and a port from another language carries those bugs along unless tests catch them.
| Bug | In safe Rust |
|---|---|
| Use after free, double free | Rejected by the compiler (ownership: one owner frees the value) |
| Dangling reference | Rejected (a reference cannot outlive its value) |
| Reading uninitialised memory | Rejected (a variable must be assigned before use) |
| Out-of-bounds index | Not undefined behaviour: the program panics with the index and length |
| Data race between threads | Rejected (see the thread on C++ threads and mutexes) |
| Null pointer dereference | Not possible in safe code: absence is an Option you must handle |
| Memory leak | Possible (reference cycles, mem::forget) |
| Deadlock | Possible |
| Logic error, wrong requirement | Possible |
unwrap() on None or Err | Possible: it panics |
| Integer overflow | Depends on the build: see below |
The last row surprises people who port from C#, Java or C. The arithmetic checks follow the build profile: a debug build panics on overflow, a release build wraps around. The same program, built both ways with rustc 1.93.0, adding the numbers 200 and 100 in a u8:
fn main() {
let v: Vec<u8> = std::env::args().skip(1).map(|a| a.parse().unwrap()).collect();
let mut total: u8 = 0;
for x in &v {
total += *x;
}
println!("total = {total}");
println!("checked = {:?}", v.iter().try_fold(0u8, |acc, &x| acc.checked_add(x)));
println!("saturating = {}", v.iter().fold(0u8, |acc, &x| acc.saturating_add(x)));
}(debug build, arguments 200 100)
thread 'main' panicked at src\bin\overflow.rs:5:9:
attempt to add with overflow
(release build, arguments 200 100)
total = 44
checked = None
saturating = 255In the release build 200 + 100 wrapped to 44 without any message. Either choose the behaviour you want in the code (checked_add returns None, saturating_add stops at the maximum, wrapping_add wraps on purpose), or set overflow-checks = true under [profile.release] in Cargo.toml if you prefer a panic in release builds too; this costs some speed. Panic and wrap-around are both defined behaviour, unlike signed overflow in C, which the C standard leaves undefined.
Common mistakes#
- Assuming "it compiles" means "it is correct". The compiler checks memory and thread safety, not the meaning of your program.
- Testing only in a debug build. Run the tests in release mode too (
cargo test --release) when the code does arithmetic that could overflow. - Using
unsafeto silence the compiler. Insideunsafethe guarantees above are your responsibility again.
Related questions#
Does safe Rust guarantee there are no crashes?#
No. A panic ends the thread (or the program) with a message, and that is a crash from a user's point of view. The thread on panics and errors explains when each is right.
Can a library I depend on contain unsafe code?#
Yes, the standard library does. The point is that the amount of unsafe is small, visible by keyword, and reviewable, instead of being the whole program.
Sources#
- The Rust Book, "Unsafe Rust": https://doc.rust-lang.org/book/ch20-01-unsafe-rust.html
- The Rust Reference, "Integer overflow": https://doc.rust-lang.org/reference/expressions/operator-expr.html#overflow
- The Cargo Book, "Profiles" (
overflow-checks): https://doc.rust-lang.org/cargo/reference/profiles.html