Unsafe Rust
Undefined behavior
What the compiler assumes never happens, and how to catch it when it does
What it means
Undefined behavior means the compiler is allowed to assume it never happens. A program that triggers it can print the expected answer, garbage, or crash, and change between builds
Common causes
- Reading or writing memory that has been freed (use-after-free)
- Reading or writing outside an allocation (buffer overflow)
- Two threads touching the same memory at once with at least one write (data race)
- Breaking the aliasing rules, e.g. writing through a raw pointer while a
&mutto the same data is still live - Producing an invalid value, such as a
boolthat isn't0or1