Skip to content

ref-as-ptr causes compiler error #13910

Open
@matthiaskrgr

Description

@matthiaskrgr

Summary

.

Lint Name

ref-as-ptr

Reproducer

I tried this code:

static mut FOO: Foo = Foo {
    field: &mut [42] as *mut [i32] as *mut i32,
};

struct Foo {
    field: *mut i32,
}

unsafe impl Sync for Foo {}

fn main() {
    assert_eq!(unsafe { *FOO.field = 69; *FOO.field }, 69);
}

I saw this happen:

warning: reference as raw pointer
 --> /home/matthias/vcs/github/glacier2/fixed/124319.rs:2:12
  |
2 |     field: &mut [42] as *mut [i32] as *mut i32,
  |            ^^^^^^^^^^^^^^^^^^^^^^^ help: try: `std::ptr::from_mut::<[i32]>(&mut [42])`
  |
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#ref_as_ptr
  = note: requested on the command line with `--force-warn clippy::ref-as-ptr`

This does not compile:

error: encountered dangling pointer in final value of mutable static
 --> /home/matthias/vcs/github/glacier2/fixed/124319.rs:1:1
  |
1 | static mut FOO: Foo = Foo {
  | ^^^^^^^^^^^^^^^^^^^

Version

rustc 1.85.0-nightly (14ee63a3c 2024-12-29)
binary: rustc
commit-hash: 14ee63a3c651bb7a243c8b07333749ab4b152e13
commit-date: 2024-12-29
host: x86_64-unknown-linux-gnu
release: 1.85.0-nightly
LLVM version: 19.1.6

Additional Labels

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: Clippy is not doing the correct thingI-false-positiveIssue: The lint was triggered on code it shouldn't haveI-suggestion-causes-errorIssue: The suggestions provided by this Lint cause an ICE/error when applied

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions