Sub topic 2
What undefined behavior means
Prerequisites
This chapter assumes you know ownership, borrowing, and lifetimes in safe Rust. It also assumes you can read references, slices, and structs, and that you can build and run a program with Cargo. You don't need to know unsafe syntax yet. The chapter on the five unsafe operations covers that.
The definition
Undefined behavior (UB) is what happens when a program breaks a rule that the language assumes is never broken. The Rust compiler is allowed to assume your program contains no UB. It optimizes with that assumption. If the assumption is false, the language makes no promise about what the program does.
"No promise" is broader than "crashes" or "gives a wrong answer". A program with UB can:
- appear to work today and fail after a compiler upgrade,
- work in debug builds and fail in release builds,
- corrupt unrelated data,
- run code paths that the source says are unreachable.
UB is a property of an execution, not of a line of code. A program is fine as long as no execution breaks the rules, and one bad input can be enough to break them.
Why compilers treat UB this way
The optimizer proves facts about your code and uses them to make it faster. Many of those facts come from rules such as "a reference is never null" or "an &mut reference is the only way to reach its data right now". If the optimizer could not rely on those rules, it would have to emit slower code that checks for every impossible case.
The cost is that the optimizer does not detect violations. It just reasons forward from the rules. Consider this function:
fn first_or_zero(values: &[u32]) -> u32 {
if values.is_empty() {
return 0;
}
values[0]
}
fn main() {
println!("{}", first_or_zero(&[]));
println!("{}", first_or_zero(&[9, 8]));
}This is safe code and has no UB. The bounds check on values[0] is redundant after is_empty, so the optimizer may remove it. That is correct only because the check in your code proves the index is valid. In unsafe code, you are the one who supplies that proof.
Safe Rust cannot cause UB
The central promise of Rust is this: if you write only safe code, and every unsafe block you depend on is correct, your program has no UB. Safe code can still panic, overflow in debug builds, deadlock, leak memory, or produce wrong output. None of those are UB.
| Behavior | UB? | Notes |
|---|---|---|
| Panic from `unwrap` on `None` | No | Defined: the thread unwinds or aborts. |
| Integer overflow in a release build | No | Defined: it wraps. |
| Index out of bounds on a slice | No | Defined: it panics. |
| Memory leak with `mem::forget` | No | Safe, though usually unwanted. |
| Deadlock | No | A logic error, not UB. |
| Dereferencing a dangling raw pointer | Yes | Needs `unsafe`. |
| Creating a `bool` with value 2 | Yes | Needs `unsafe`. |
| Data race on non-atomic memory | Yes | Needs `unsafe` to introduce. |
The unsafe keyword marks the places where this guarantee is no longer checked by the compiler. Inside such a place, you take over the obligation to avoid UB.
What unsafe does not turn off
An unsafe block does not disable the borrow checker, type checking, or lifetime checking. It only unlocks a short list of extra operations. This code still fails to compile:
fn main() {
let s = String::from("hello");
unsafe {
let moved = s;
println!("{}", s);
drop(moved);
}
}The compiler reports use of a moved value even inside unsafe. Later chapters cover exactly which operations unsafe unlocks. For now, remember that unsafe means "I checked this myself", not "no checks".
Common sources of UB
The Rust reference keeps a list of behaviors considered undefined. It is not guaranteed to be complete, so treat it as a minimum. The main groups are below.
Invalid memory access
Reading or writing through a pointer is UB if the pointer is null, dangling, or out of bounds of the allocation it came from. A pointer to a local variable becomes dangling when the variable goes out of scope.
fn dangling() -> *const i32 {
let x = 10;
&x as *const i32
}
fn main() {
let p = dangling();
println!("pointer created: {}", !p.is_null());
// Dereferencing `p` here would be UB: `x` no longer exists.
}Creating the pointer and checking is_null is safe. Reading *p is the UB. This is why the compiler lets you make raw pointers freely but demands unsafe to use them.
Misaligned access
Each type has an alignment: the address of a value of that type must be a multiple of a given number. A u32 has alignment 4. Dereferencing a *const u32 whose address is not a multiple of 4 is UB, even on hardware that tolerates unaligned loads. When you must read from unaligned memory, use read_unaligned:
fn main() {
let bytes: [u8; 8] = [0, 1, 0, 0, 0, 2, 0, 0];
// SAFETY: the pointer is in bounds (offset 1 + 4 bytes <= 8), and
// `read_unaligned` places no alignment requirement on it.
let value = unsafe {
let p = bytes.as_ptr().add(1) as *const u32;
p.read_unaligned()
};
println!("{value:#x}");
}Invalid values
Some types have bit patterns that are not valid values. Producing such a value is UB at the moment it is produced, even if you never use it.
boolmust be 0 or 1.charmust be a Unicode scalar value (not a surrogate, not above0x10FFFF).- References and
Boxmust be non-null, aligned, and point to valid data. - Enums must hold one of their declared discriminants.
!can never be produced.- A
strmust be valid UTF-8 when used as one.
fn main() {
let byte: u8 = 2;
// `char::from_u32` checks validity and returns None for bad values.
println!("{:?}", char::from_u32(0xD800));
println!("{:?}", char::from_u32(0x41));
// `std::mem::transmute::<u8, bool>(byte)` would be UB; this is the safe way:
println!("{}", byte != 0);
}Aliasing violations
Rust's reference rules say that while a &mut T is live, no other reference or pointer may be used to access the same data, except through that &mut T. Shared references &T may overlap each other, but the data cannot be mutated while they are live (unless it sits inside UnsafeCell, the building block under Cell and Mutex). The optimizer relies on this to keep values in registers and reorder loads.
Raw pointers don't carry this guarantee, which is one reason they need unsafe to dereference. The danger is turning raw pointers back into references. If you create two &mut references to the same value, you have UB, even if you never use them at the same time in a way that looks harmful.
Data races
A data race occurs when two threads access the same memory at the same time, at least one access is a write, and at least one access is not atomic. Data races are UB. A race condition in logic, such as two threads updating an atomic counter in the wrong order, is a bug but not UB.
Breaking a function's contract
Functions in the standard library document preconditions. slice::from_raw_parts requires a non-null, aligned pointer to initialized data, valid for the full length, with a total size no larger than isize::MAX. Breaking a documented precondition of an unsafe function is UB, even if the code appears to work.
Why "it ran fine" proves nothing
UB has no fixed symptom. The same source can behave differently depending on the optimization level, the target CPU, or the surrounding code. A test passing is evidence only that this particular compile and run did not expose the problem.
This is why unsafe code needs different habits. You cannot test your way to confidence. You need a stated argument for why each operation is valid, which later chapters call a safety contract, and tools such as Miri that check executions against the rules.
Soundness
A piece of code is sound if no use of it from safe code can cause UB. A safe function that wraps unsafe code is unsound if some argument, which safe code can legally pass, makes it break a rule. Soundness is judged on the whole safe interface, not on the inputs you tested.
This function is unsound:
fn get_unchecked_bad(values: &[i32], index: usize) -> i32 {
// SAFETY: none. This is wrong, because `index` is not checked.
unsafe { *values.get_unchecked(index) }
}
fn main() {
let data = [1, 2, 3];
println!("{}", get_unchecked_bad(&data, 1));
// get_unchecked_bad(&data, 10) compiles and would be UB.
}Safe code can call it with 10, and nothing stops that. The fix is either to check the index and panic, or to mark the function unsafe and document that index < values.len(). Both choices are valid. The wrong choice is a safe signature with an unchecked body.
Debugging mindset
When you suspect UB:
- Run the program under Miri (
cargo +nightly miri run). It interprets the program and reports many violations, such as out-of-bounds access, dangling pointers, and some aliasing errors. - Re-read each
unsafeblock and write down the rule it relies on. - Reduce the unsafe region. Move checks into safe code before the unsafe operation.
- Don't "fix" UB by changing optimization levels or adding prints. That changes the symptom, not the cause.
Exercise
A safe function fn nth(values: &[u8], i: usize) -> u8 has the body unsafe { *values.as_ptr().add(i) }. All your tests pass. Is the function sound? What is the smallest change that makes it sound without changing its signature?
Show answer
It is unsound. Safe code can call nth(&[1], 5), which reads past the end of the slice. That is UB regardless of whether tests pass. The smallest fix is to check the bound first, for example with assert!(i < values.len()); before the unsafe block, or to use values[i], which panics instead of causing UB.
Exercise
Which of these are UB? (a) An Option::unwrap on None. (b) Reading through a pointer to a local variable after the variable's scope ended. (c) Adding one to u8::MAX in a release build. (d) Two threads writing to the same non-atomic u32 without synchronization.
Show answer
(b) and (d) are UB. (a) panics, which is defined. (c) wraps in a release build, which is defined (and panics in debug builds).