rust-lang / rust-lang/rust-clippy

Lint for large on-stack temporary values

Open
#15,809 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

What it does

This lint warns unintentional large temporary values which may cause an overflowed stack.

Taking this function definition:

const LENGTH: usize = 1048576;

fn foo(buf: &[u8; LENGTH]) {
    let _a = buf;
}

On the signature, a thin ref &[u8; LENGTH] ensures the argument passed in should have exactly this size. Out of the function, array.try_into().unwrap() can be used as an assertion to the array size. However,

fn main() {
    let buf = vec![0_u8; LENGTH];
    // No! equivalent to: foo(&<[u8; LENGTH]>::try_from(buf).unwrap())
    foo(&buf.try_into().unwrap());
}

One may carelessly write a function call like above (I searched and found many occurrences like this on GitHub). Note, it will create a [u8; LENGTH] temporary value that is then referenced and passed to the function. This temporary value may cause an overflowed stack.

In this case above, due to different stack size limit on the two platforms, it runs smoothly on Linux but Stack overflow encounters on Windows. This may be tricky somehow.

Advantage
  • Avoid unneeded stack temporary values and potential stack overflow errors.
Drawbacks

No response

Example
let buf: Vec<T> = ...
foo(&buf.try_into().unwrap());

Could be written as:

let buf: Vec<T> = ...
foo(<&[T; LENGTH]>::try_from(&buf[..]).unwrap());

Or,

let buf: Vec<T> = ...
foo((&buf[..]).try_into().unwrap());
Comparison with existing lints

We have large_stack_arrays lint but this is unable to detect such cases.

Additional Context

No response

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 by reviewing the existing large_stack_arrays lint and the examples in this issue to understand which temporary conversions should be diagnosed. Determine how the proposed lint would distinguish a large stack temporary from a reference conversion, and consider the shown examples as the completion criteria.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
tooling
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.