Skip to content

Nightly: unsafe code is allowed outside unsafe blocks when the code is unreachable #45087

Closed
@Thiez

Description

@Thiez

I'm not sure if this is a feature or a bug, but the compiler behaves differently for the following program on stable, beta, and nightly:

fn main() {
    return;
    let _ = ();
    *(&true as *const bool);
}

On stable:

error[E0133]: dereference of raw pointer requires unsafe function or block
 --> src/main.rs:4:5
  |
4 |     *(&true as *const bool);
  |     ^^^^^^^^^^^^^^^^^^^^^^^ dereference of raw pointer

error: aborting due to previous error

On beta:

warning: unreachable statement
 --> src/main.rs:3:5
  |
3 |     let _ = ();
  |     ^^^^^^^^^^^
  |
  = note: #[warn(unreachable_code)] on by default

error[E0133]: dereference of raw pointer requires unsafe function or block
 --> src/main.rs:4:5
  |
4 |     *(&true as *const bool);
  |     ^^^^^^^^^^^^^^^^^^^^^^^ dereference of raw pointer

error: aborting due to previous error

On nightly:

warning: unreachable statement
 --> src/main.rs:3:5
  |
3 |     let _ = ();
  |     ^^^^^^^^^^^
  |
  = note: #[warn(unreachable_code)] on by default

Note that wrapping the final statement in an unsafe block will allow the program to compile on all three versions, but on nightly the compiler will complain:

warning: unnecessary `unsafe` block
 --> src/main.rs:4:5
  |
4 |     unsafe { *(&true as *const bool); }
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ unnecessary `unsafe` block
  |
  = note: #[warn(unused_unsafe)] on by default

I suppose that the compiler is technically correct, because dead code tells no tales cannot cause memory unsafety, so no unsafe block is needed... but the current situation does seem like an accident, as the compiler does perform other checks on dead code (typechecking, borrow-checking, ...).

Metadata

Metadata

Assignees

Labels

C-bugCategory: This is a bug.P-highHigh priorityT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.regression-from-stable-to-betaPerformance or correctness regression from stable to beta.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions