FAQ - Help and questions

Which kinds of bugs does Rust prevent, and which are still possible?

#why-rust#porting#safetypublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

In safe Rust the compiler prevents use-after-free, double free, dangling references, data races and use of uninitialised memory. It does not prevent logic errors, panics, deadlocks, leaks or integer overflow, which wraps silently in a release build unless you ask otherwise. Know the line to know what to test.

Checked with rustc 1.93.0, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

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.

BugIn safe Rust
Use after free, double freeRejected by the compiler (ownership: one owner frees the value)
Dangling referenceRejected (a reference cannot outlive its value)
Reading uninitialised memoryRejected (a variable must be assigned before use)
Out-of-bounds indexNot undefined behaviour: the program panics with the index and length
Data race between threadsRejected (see the thread on C++ threads and mutexes)
Null pointer dereferenceNot possible in safe code: absence is an Option you must handle
Memory leakPossible (reference cycles, mem::forget)
DeadlockPossible
Logic error, wrong requirementPossible
unwrap() on None or ErrPossible: it panics
Integer overflowDepends 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:

src/main.rsrust
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)));
}
text
(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 = 255

In 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 unsafe to silence the compiler. Inside unsafe the guarantees above are your responsibility again.

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#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet