rust-lang / rust-lang/rust-clippy

Lint for returning raw pointers to temporary stack locations that don't outlive the statement that creates them

Open
#10,959 4 comments 4 reactions 1 assignee View on GitHub

@Centri3 is already working on this.

Since Jun 15, 2023.

A-lint
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

What it does

The general pattern of the code this should complain about is something like

let x = &(some expression that is stored in a temporary variable on the stack) as *const T;

Similar with using addr_of! instead of & and casts, etc.

Concrete examples this would catch are

let x = &(1 + 2) as *const i32;
let x = &(x as *const i32) as *const *const i32;

In both cases the part in the parenthesis is stored in a temporary stack location that is no longer valid after the whole statement.

It should however not catch

let x = &(*ptr).x as *const T;
let x = &(some_variable) as *const T;
Advantage

Whatever pointer is created there is pointing to no longer valid stack memory, so any usage afterwards will be unsound

Drawbacks

Theoretically this could cause false positives but the only case I can see where the resulting code is not unsound is if you cast the pointer to an usize and do some calculations with it. I don't see how that could lead to any useful results in such a context though.

Example

See examples above

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.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.