Description
Summary
Reading/writing a place requires that place to be based on an aligned pointer, but taking the reference of a place only requires the referenced place to be aligned. These facts together mean that {*&(*ptr).0}
is a semantically weaker operation than {(*ptr).0}
, but clippy::deref_addrof
will suggest changing the former to the latter, which potentially introduces UB to a program.
This might be considered reasonable (i.e. not a false positive), as semantically relying on this is unreasonably subtle. However, the lint also still fires when using &raw
, which should not be happening when the place is potentially based on a misaligned pointer.
Note: the lint is still useful and should be fired for immediately dereferencing a pointer (*&raw
) when the place is not based on a (potentially misaligned) pointer, as it is still an operational no-op when the place is based on an aligned pointer (or reference), and removing such allows *&raw
to semantically indicate lowering the implied alignment of a place.
Lint Name
clippy::deref_addrof
Reproducer
I tried this code:
unsafe fn foo(ptr: *mut (u32, u64)) {
*&mut (*ptr).0 = 5;
let v = *&(*ptr).0;
assert_eq!(v, 5);
}
I saw this happen:
warning: immediately dereferencing a reference
--> src/main.rs:4:5
|
4 | *&mut (*ptr).0 = 5;
| ^^^^^^^^^^^^^^ help: try: `(*ptr).0`
|
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#deref_addrof
= note: `#[warn(clippy::deref_addrof)]` on by default
warning: immediately dereferencing a reference
--> src/main.rs:5:13
|
5 | let v = *&(*ptr).0;
| ^^^^^^^^^^ help: try: `(*ptr).0`
|
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#deref_addrof
I expected to see this happen:
Applying the warnings' suggested fix should not introduce UB.
Version
rustc: 1.82.0-nightly (2024-08-15 2c93fabd98d2c183bcb3)
clippy; 0.1.82 (2024-08-15 2c93fab)
miri: 0.1.0 (2024-08-15 2c93fab)
Additional Labels
@rustbot label +I-suggestion-causes-ub
:cheeky: