Can undefined behavior that is theoretically reachable, but not reached in practice cause problems? #454
Description
This is a question that is in my opinion important when dealing with the risk of undefined behavior, but is currently not clearly adressed in the nomicon (or any other materials I could find online):
If some part of a program contains undefined behavior that is reachable, but is then executed with inputs where that part of the program won't be reached, is the behavior of that specific program execution well defined or not? In other words, is the impact of undefined behavior limited to specific program executions where undefined behavior is invoked or can it affect all possible executions of the program?
For a more concrete example, say I have this program:
use std::{env, hint::unreachable_unchecked};
fn main() {
let args: Vec<String> = env::args().collect();
let value = args[1].parse::<i32>().unwrap();
if value == 0 {
// Something that caueses undefined behavior here. unreachable_unchecked() is used as an example,
// but it could be anything, e.g. dereferencing a dangling pointer or creating two mutable references to the same value.
unsafe { unreachable_unchecked() };
}
println!("Value: {}", value);
}
If I run this program with an argument of 1
, is there any risk of undefined behavior in that specific run of the program?