Skip to content

False positive const-UB check on NonNull pointer #133523

@JakobDegen

Description

I tried this code:

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    A-const-evalArea: Constant evaluation, covers all const contexts (static, const fn, ...)C-bugCategory: This is a bug.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.T-langRelevant to the language team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions