Skip to content

Detect expressions where size_of::<T>() is an argument to ptr::copy/ptr::copy_nonoverlapping and T is the type of the pointee. #6381

Closed
@thomcc

Description

@thomcc

What it does

What does this lint do?

Detects expressions where size_of::<T>() is used in the size argument to ptr::copy / ptr::copy_nonoverlapping / etc, where T is the type of the pointers passed in as arguments.

It should not fire if T is a different type, as it's common and correct to use this for byte copies.

Note:

This can happen because the docs for this function say:

copy_nonoverlapping is semantically equivalent to C's memcpy, but with the argument order swapped.

Which is slightly inaccurate, since memcpy takes the size in bytes despite accepting pointers of any type (in C, anyway — in C++ you'll have to explicitly cast to coerce to void*).

(TODO(me): file a docs bug about this) rust-lang/rust#79430

Categories (optional)

  • Kind: clippy::correctness probably.

What is the advantage of the recommended code over the original code

copy_nonoverlapping already incorporates size_of::<T>() into the offset calculation, so it avoids reads/writes out of bounds, probably.

Drawbacks

It's possible the original code isn't wrong, but if so it would be highly confusing.

Example

Assuming a and b are pointers to T:

ptr::copy_nonoverlapping(a, b, std::mem::size_of::<T>() * N);

Could be written as:

ptr::copy_nonoverlapping(a, b, N);

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lintArea: New lints

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions