Skip to content

FP ptr-cast-constness #11317

@matthiaskrgr

Description

@matthiaskrgr

Summary

.

Lint Name

ptr-cast-constness

Reproducer

I tried this code:

#![allow(invalid_reference_casting)]

fn main() {
    let target = 42;
    // Make sure raw ptr with raw tag cannot mutate frozen location without breaking the shared ref.
    let r#ref = ⌖ // freeze
    let ptr = r#ref as *const _ as *mut _; // raw ptr, with raw tag
    unsafe { *ptr = 42 }; //~ ERROR: /write access .* only grants SharedReadOnly permission/
    let _val = *r#ref;
}

I saw this happen:

warning: `as` casting between raw pointers while changing only its constness
 --> src/main.rs:7:15
  |
7 |     let ptr = r#ref as *const _ as *mut _; // raw ptr, with raw tag
  |               ^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try `pointer::cast_mut`, a safer alternative: `(r#ref as *const _).cast_mut()`
  |
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#ptr_cast_constness
  = note: requested on the command line with `-W clippy::ptr-cast-constness`

rustfix error:

The following errors were reported:
error[E0699]: cannot call a method on a raw pointer with an unknown pointee type
 --> src/main.rs:7:35
  |
7 |     let ptr = (r#ref as *const _).cast_mut(); // raw ptr, with raw tag
  |                                   ^^^^^^^^

error: aborting due to previous error

Version

rustc 1.73.0-nightly (f88a8b71c 2023-08-08)
binary: rustc
commit-hash: f88a8b71cebb730cbd5058c45ebcae1d4d9be377
commit-date: 2023-08-08
host: x86_64-unknown-linux-gnu
release: 1.73.0-nightly
LLVM version: 17.0.0

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