Explanation of code example.
The only allowed representation of bool is either 0 or 1.
Therefore, transmuting 3_u8 to bool violates its validity invariant and is undefined behavior.
fn example_function() -> bool {
unsafe {
std::transmute<bool>(3_u8)
}
}
A necessary condition to read the value behind a pointer is that it points to a valid allocation.
This is never the case for a null pointer, therefore reading it is undefined behavior.
See the safety precondition of std::ptr::read .
fn example_function() {
unsafe {
std::ptr::read(std::ptr::null());
}
}
|