False positive const-UB check on NonNull
pointer #133523
Open
Description
opened on Nov 27, 2024
use std::ptr::NonNull;
const X: NonNull<()> = {
let r: &'static u16 = &0;
let p = unsafe { std::mem::transmute::<_, *mut ()>(r) };
let p = p.wrapping_byte_add(3);
unsafe { NonNull::new_unchecked(p) }
};
I expected to see this happen: Compiles. This code cannot be UB, as the alignment on the static guarantees that the produced pointer has odd address and therefore is non-null.
Instead, this happened:
error[E0080]: it is undefined behavior to use this value
--> src/lib.rs:3:1
|
3 | const X: NonNull<()> = {
| ^^^^^^^^^^^^^^^^^^^^ constructing invalid value: encountered a potentially null pointer, but expected something that cannot possibly fail to be greater or equal to 1
|
= note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior.
= note: the raw bytes of the constant (size: 8, align: 8) {
╾───alloc3+0x3<imm>───╼ │ ╾──────╼
}
For more information about this error, try `rustc --explain E0080`.
The check seems to know that it might sometimes be wrong, but this isn't a case where the rules around UB are unclear - the rules around what pointers you can put in a NonNull
are very clear.
Meta
All versions of Rust since 1.61 where the necessary operations were stabilized in const
Activity