rust-lang / rust-lang/rust-clippy

`manual_memcpy` lints against slices but not pointer arythmetics

Open
#13,859 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

C-bug I-false-negative
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

Summary

manual_memcpy should be able to suggest using core::ptr::copy_nonoverlapping when relevant

Lint Name

manual_memcpy

Reproducer

I tried this code:

#![allow(unreachable_code)]

fn main() {
    let p: *const u32 = todo!();
    let mut dest = [0u32; 10];
    
    for i in 0..10 {
        dest[i] = unsafe {*p.add(i)};
    }
}

I expected to see this happen:

Clippy should suggest to replace it with the following (maybe using core::ptr::copy if clippy can't assert from type information (such as one being a mutable reference) that the pointers don't overlap).

#![allow(unreachable_code)]

fn main() {
    let p: *const u32 = todo!();
    let mut dest = [0u32; 10];
    
    unsafe {
        core::ptr::copy_nonoverlapping(p, dest.as_mut_ptr(), 10);
    }
}

Instead, this happened:

The cilppy lints needless_range_loops was triggered:

warning: the loop variable `i` is used to index `dest`
 --> src/main.rs:7:14
  |
7 |     for i in 0..10 {
  |              ^^^^^
  |
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_range_loop
  = note: `#[warn(clippy::needless_range_loop)]` on by default
help: consider using an iterator and enumerate()
  |
7 |     for (i, <item>) in dest.iter_mut().enumerate() {
  |         ~~~~~~~~~~~    ~~~~~~~~~~~~~~~~~~~~~~~~~~~

warning: `playground` (bin "playground") generated 2 warnings
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.58s
Version
Nightly channel

Build using the Nightly version: 1.85.0-nightly

(2024-12-19 9e136a30a965bf4e63f0)

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start at the manual_memcpy lint entry point and reproduce the Rust example from the issue. Done means pointer arithmetic is recognized and the lint suggests core::ptr::copy_nonoverlapping, or core::ptr::copy when non-overlap cannot be established, rather than only producing the range-loop warning.

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
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.