-
-
Notifications
You must be signed in to change notification settings - Fork 14.8k
Warn that *const T as *mut T is Undefined Behavior #66136
Copy link
Copy link
Open
Labels
A-lintsArea: Lints (warnings about flaws in source code) such as unused_mut.Area: Lints (warnings about flaws in source code) such as unused_mut.C-feature-requestCategory: A feature request, i.e: not implemented / a PR.Category: A feature request, i.e: not implemented / a PR.T-langRelevant to the language teamRelevant to the language team
Metadata
Metadata
Assignees
Labels
A-lintsArea: Lints (warnings about flaws in source code) such as unused_mut.Area: Lints (warnings about flaws in source code) such as unused_mut.C-feature-requestCategory: A feature request, i.e: not implemented / a PR.Category: A feature request, i.e: not implemented / a PR.T-langRelevant to the language teamRelevant to the language team
Type
Fields
Give feedbackNo fields configured for issues without a type.
Casting a
*const Tto*mut Tmay lead to memory corruption since it allows mutation of shared state. Even if the*const Thappened to be unique, it is still undefined behavior and the optimizer may break such code in interesting ways. In a nutshell, this is as bad as transmuting a&into&mut. The compiler should warn against doing this.Update: as pointed out below, there are cases when that does not immediately trigger UB, but in those cases there is no reason to do this in the first place.
This often occurs when people try to consume a data structure and create a new one from it, e.g.
in which case the proper solution is to rewrite it as
This also may happen when people try to mutate shared state through a
&, in which case they need aCell,RefCellor anUnsafeCellinstead.Playground with a real-world snippet that fails MIRI: https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=b28a15e3d99616b03caafdd794550946
This pattern seems to be quite widespread - quoting @RalfJung on Zulip:
I have already requested a Clippy lint for this, but this looks important enough to warn against by default, without relying on optional tooling to catch this.