Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is undefined behavior possible in safe Rust?

Is there any way to achieve undefined behavior in Rust without using unsafe?

Of course, such behavior can be wrapped by a third-party library in a "safe" function so let's assume we're using only the standard one.

like image 788
passing_through Avatar asked Jun 24 '20 16:06

passing_through


People also ask

What does unsafe Rust allow?

Unsafe Superpowers Those superpowers include the ability to: Dereference a raw pointer. Call an unsafe function or method. Access or modify a mutable static variable.

Is Rust completely safe?

The safety guarantee is one of the most important aspects of Rust; Rust is memory-safe, null-safe, type-safe, and thread-safe by design. If the compiler detects unsafe code, it will refuse to compile that code by default.


1 Answers

Absolutely, but any such case is a bug with Rust or the standard libary.

My favorite example is LLVM loop optimization can make safe programs crash, which actually occurs due to a poor interaction of Rust and LLVM semantics:

pub fn oops() {
    (|| loop {
        drop(42)
    })()
}

Compiled with optimizations on Rust 1.49.0, this produces the assembly:

playground::oops:
    ud2

such behavior can be wrapped by a third-party library in a "safe" function so let's assume we're using only the standard one

The standard library is a "third-party library", so I don't get the distinction.

like image 144
Shepmaster Avatar answered Nov 15 '22 09:11

Shepmaster