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

vec as_ptr/as_mut_ptr should have a deny lint #2637

Closed
TheDan64 opened this issue Apr 6, 2018 · 2 comments
Closed

vec as_ptr/as_mut_ptr should have a deny lint #2637

TheDan64 opened this issue Apr 6, 2018 · 2 comments
Labels
A-lint Area: New lints L-correctness Lint: Belongs in the correctness lint group

Comments

@TheDan64
Copy link

TheDan64 commented Apr 6, 2018

Hi!

Similarly to the temporary_cstring_as_ptr lint, a common mistake I've run into when dealing with FFI a bunch is immediately trying to get a raw pointer from an initialized vec:

let ptr = vec![0; 4].as_mut_ptr();

This is a really easy way to get a dangling pointer and can be easily overlooked. It would be great if we had a clippy lint for it and as_ptr as well.

There are quite a few ways to initialize a vec that should be also taken into consideration, for example:

let ptr = Vec::from_elem(0, 4).as_mut_ptr();
@oli-obk
Copy link
Contributor

oli-obk commented Apr 7, 2018

we can in fact lint any function call returning a Vec by value that is immediately followed by a call to as_mut_ptr.

@phansch phansch added A-lint Area: New lints L-correctness Lint: Belongs in the correctness lint group labels Apr 24, 2018
@y21
Copy link
Member

y21 commented Dec 10, 2024

Closing as this lint exists in the compiler now

warning: a dangling pointer will be produced because the temporary `Vec<i32>` will be dropped
 --> src/main.rs:2:22
  |
2 | let ptr = vec![0; 4].as_mut_ptr();
  |           ---------- ^^^^^^^^^^ this pointer will immediately be invalid
  |           |
  |           this `Vec<i32>` is deallocated at the end of the statement, bind it to a variable to extend its lifetime
  |
  = note: pointers do not have a lifetime; when calling `as_mut_ptr` the `Vec<i32>` will be deallocated at the end of the statement because nothing is referencing it as far as the type system is concerned
  = help: for more information, see <https://doc.rust-lang.org/reference/destructors.html>
  = note: `#[warn(dangling_pointers_from_temporaries)]` on by default

@y21 y21 closed this as completed Dec 10, 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

No branches or pull requests

4 participants