Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Lint suggestion: write to raw pointer with drop glue #4294

Open
RalfJung opened this issue Jul 22, 2019 · 3 comments · May be fixed by #13866
Open

Lint suggestion: write to raw pointer with drop glue #4294

RalfJung opened this issue Jul 22, 2019 · 3 comments · May be fixed by #13866
Labels
A-lint Area: New lints L-correctness Lint: Belongs in the correctness lint group

Comments

@RalfJung
Copy link
Member

One of the subtle aspects of *ptr = val where ptr is a raw pointer is that this will drop the old contents stored behind that pointer. On the one hand that might not be surprising because this is the same for mutable references, but on the other hand raw pointers are often used to point to invalid/uninitialized data, and then this is an easy way to cause a double-drop or to drop some garbage data. I have made this mistake myself and seen it a few times "out there".

So I think it'd be a good idea to lint against *ptr = val when ptr: *mut T and T has drop glue. The lint should recommend to use ptr.write(val) instead, which does not drop. Code that wants to drop should explicitly do ptr.drop_in_place().

@flip1995 flip1995 added L-correctness Lint: Belongs in the correctness lint group A-lint Area: New lints labels Jul 22, 2019
@gnzlbg
Copy link
Contributor

gnzlbg commented Jul 23, 2019

As in, the lint should suggest to re-write:

*ptr = val;

as

ptr.drop_in_place();
ptr.write(val);

and contain a note that say something along these lines: "If the memory pointed to by ptr is not valid, the behavior of trying to drop that memory using ptr.drop_in_place(); is undefined. This can happen if, for example, *ptr = val is used to initialize uninitialized memory".

@flip1995
Copy link
Member

flip1995 commented Jul 23, 2019

I agree. I would keep the note on the lint message short though ("ptr.drop_in_place() could be undefined behavior") and put the long explanation in the documentation.

@Robert4S
Copy link

spent a bunch of time debugging *ptr = val where ptr is uninitialised, this would've helped a ton.

@lukaslueg lukaslueg linked a pull request Dec 22, 2024 that will close this issue
lukaslueg added a commit to lukaslueg/rust-clippy that referenced this issue Dec 22, 2024
lukaslueg added a commit to lukaslueg/rust-clippy that referenced this issue Dec 22, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-lint Area: New lints L-correctness Lint: Belongs in the correctness lint group
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants