Skip to content

ManuallyDrop allows storing invalid references in consts and statics. #159701

Description

@theemathas

This is not necessarily a bug, but I think it's worth noting as an unintended(?) consequence of the MaybeDangling changes, probably in #150446. See also #118166. Note that the ManuallyDrop type currently contains a MaybeDangling inside.

The following code compiles since 1.96.0:

use std::mem::{ManuallyDrop, transmute};
const DATA: ManuallyDrop<&i32> = unsafe { transmute(4_usize) };

(Note: We're using 4 since i32 has alignment 4.)

In 1.95.0, it produced the following error:

error[E0080]: constructing invalid value at .value.0: encountered a dangling reference (0x4[noalloc] has no provenance)
 --> <source>:2:1
  |
2 | const DATA: ManuallyDrop<&i32> = unsafe { transmute(4_usize) };
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ it is undefined behavior to use this value
  |
  = 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) {
              04 00 00 00 00 00 00 00                         │ ........
          }

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0080`.

Attempting to use the const in a pattern results in a strange diagnostic:

use std::mem::{ManuallyDrop, transmute};
const DATA: ManuallyDrop<&i32> = unsafe { transmute(4_usize) };
fn main() {
    if let DATA = DATA {}
}
error: constant DATA cannot be used as pattern
 --> src/main.rs:4:12
  |
4 |     if let DATA = DATA {}
  |            ^^^^
  |
  = note: constants that reference mutable or external memory cannot be used as patterns

Is this the correct behavior?

cc @WaffleLapkin @RalfJung

Meta

Tested on 1.99.0-nightly (2026-07-20 87e5904f5eb6398af6b2) on the playground

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-const-evalArea: Constant evaluation, covers all const contexts (static, const fn, ...)C-discussionCategory: Discussion or questions that doesn't represent real issues.T-langRelevant to the language teamT-opsemRelevant to the opsem team

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions