Undefined behavior, often shortened to UB, occurs when unsafe code violates a safety rule and the language no longer promises what execution will do. Rust uses unsafe blocks to permit operations whose safety must be guaranteed by the programmer. section 16.4.2 section 16.4.4
Two examples show why UB can look harmless at first:
- A mutable static can produce a data race when several threads update it simultaneously. Small tests may print the expected value, while larger runs lose increments and produce varying results. section 16.4.2
- An _unchecked method skips a check. Calling Option::unwrap_unchecked() on Some(10) works, but calling it on None can terminate the program with a core dump. section 16.4.4
- Safe alternatives such as Arc<Mutex> preserve controlled access, while ordinary checked methods avoid relying on an assumption the compiler cannot verify. section 16.4.2 section 16.4.4
A race hidden by a successful test
Ten threads incrementing a mutable static ten times may print 100. Increasing the workload to 1,000 threads and 1,000 increments can instead print values such as 959,696 or 825,266, because simultaneous reads and writes overwrite one another. section 16.4.2
Compiler feedback identifies mutable static access as unsafe and names aliasing violations and data races as possible causes of undefined behavior. section 16.4.2






