Skip to content

Struct tail ordered differently when unsizing #112048

Closed
@y21

Description

@y21

I tried to make the MRE shorter, but this code is very sensitive to changes.

I tried this code under Miri (playground):

#![forbid(unsafe_code)]

use std::ptr::NonNull;

trait Trace {}
impl Trace for Box<i32> {}

struct GcNode<T: ?Sized> {
  refcount: u64,
  next: Option<NonNull<GcNode<dyn Trace>>>,
  value: T,
}

fn main() {
  let node: Box<GcNode<dyn Trace>> = Box::new(GcNode {
      refcount: 0,
      next: None,
      value: Box::new(0),
  });
  dbg!(node.refcount);
}

I expected to see this happen: no error.

Instead, this happened:

error: Undefined Behavior: using uninitialized data, but this operation requires initialized memory
  --> src/main.rs:20:3
   |
20 |   dbg!(node.refcount);
   |   ^^^^^^^^^^^^^^^^^^^ using uninitialized data, but this operation requires initialized memory
   |
   = help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior
   = help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information
   = note: BACKTRACE:
   = note: inside `main` at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/std/src/macros.rs:352:13: 352:16
   = note: this error originates in the macro `dbg` (in Nightly builds, run with -Z macro-backtrace for more info)

Meta

rustc --version --verbose:

❯ rustc -Vv
rustc 1.71.0-nightly (cca7ee581 2023-05-27)
binary: rustc
commit-hash: cca7ee58110726983951a19d5fb7316d9243925d
commit-date: 2023-05-27
host: x86_64-unknown-linux-gnu
release: 1.71.0-nightly
LLVM version: 16.0.4

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-layoutArea: Memory layout of typesC-bugCategory: This is a bug.I-unsoundIssue: A soundness hole (worst kind of bug), see: https://en.wikipedia.org/wiki/SoundnessP-criticalCritical priorityregression-from-stable-to-betaPerformance or correctness regression from stable to beta.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions