rust-lang / rust-lang/rust-clippy
Prevent Getting a Raw Pointer to a Temporary
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 13.5k
- Forks
- 2.2k
- Avg merge
- 2d 10h
- Merged PRs (30d)
- 32
Description
What it does
The borrow checker prevents users from borrowing content from temporaries.
The following code...
fn mistake() {
let hello = String::from("hello").as_str();
hello.to_string();
}
gives this compiler error:
error[E0716]: temporary value dropped while borrowed
--> src/main.rs:4:17
|
4 | let hello = String::from("hello").as_str();
| ^^^^^^^^^^^^^^^^^^^^^ - temporary value is freed at the end of this statement
| |
| creates a temporary which is freed while still in use
5 | hello.to_string();
| ----- borrow later used here
|
= note: consider using a `let` binding to create a longer lived value
However, the same mistakes with raw pointers is not caught. This is almost always a mistake which can lead to use after free.
Luckily, most standard library APIs are designed to not make this mistake possible, but for some like CString::as_raw there is already a clippy lint.
However, for custom smart pointer types, this issue is not caught by clippy (although it is caught by miri).
Categories (optional)
- Kind:
clippy::correctness
What is the advantage of the recommended code over the original code
The use of a pointer to a temporary is almost guaranteed to be incorrect.
Drawbacks
None.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reviewing the existing temporary_cstring_as_ptr Clippy lint and the Rust examples in the issue, then compare the custom smart-pointer case with Miri's behavior. Done means Clippy detects raw pointers obtained from temporaries, including the custom smart-pointer scenario, without flagging valid code.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- devtools
- Issue type
- Feature
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100