rust-lang / rust-lang/rust-clippy
Lint Suggestion: Pointer offset with vec reference
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
Fires upon calling one of the pointer offset_from methods (including byte_... and ..._unsigned) when the origin parameter is &Vec<T> or &mut Vec<T>.
Advantage
Prevents UB.
The user likely intended to call .as_ptr() on the vec before passing it in, but forgetting to do so results in the reference (to the vec variable, not the vec's own pointer) being silently converted to a pointer instead, which will of course have a completely different address and provenance than the heap allocation they likely intended to use.
Drawbacks
May or may not have false positives when working with nested vecs, where the given vec reference is itself part of a heap allocation, rather than being a local variable.
Example
fn mutate_vec(vec: &mut Vec<i32>) {
vec.push(9);
let nine = vec.last().unwrap();
let ptr = std::ptr::from_ref(nine);
let offset = unsafe { ptr.byte_offset_from_unsigned(vec) }; // !! UB !!
}
Could be written as:
fn mutate_vec(vec: &mut Vec<i32>) {
vec.push(9);
let nine = vec.last().unwrap();
let ptr = std::ptr::from_ref(nine);
let offset = unsafe { ptr.byte_offset_from_unsigned(vec.as_ptr()) }; // All good
}
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
No implementation file, test, or entry point is named. Start by reviewing the pointer offset methods and the provided Rust examples, then identify the existing Clippy lint patterns that would govern detection and false positives. Done means the proposed lint consistently flags the described &Vec and &mut Vec origins while accounting for the nested-Vec concern.
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