Skip to content

New lint: creation of huge array on the stack #4520

Open
@Shnatsel

Description

@Shnatsel

The following code will segfault on playground due to stack overflow:

fn do_stuff() {
    let data = [0; 10000000];
}

The problem is that Rust arrays are created on the stack, but this array is too large to fit on the stack.

What's worse, the naive solution doesn't work either:

fn do_stuff() {
    let data = Box::new([0; 10000000]);
}

This still instantiates the array on the stack and segfaults. The proper solution is this:

fn do_stuff() {
    let data = vec![0; 10000000].into_boxed_slice();
}

This issue is particularly tricky if the array size is dynamic, and does not typically manifest on tests, resulting in unexpected crashes in production. Example:

fn do_stuff(len: usize) {
    let data = [0; len];
}

Here len can be set to an arbitrarily large number that would overflow the stack. Only length values of types u8, i8, u16, i16 are definitely safe. The solution is to use one of them or create the array on the heap as described above.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lintArea: New lintsE-hardCall for participation: This a hard problem and requires more experience or effort to work onL-suggestionLint: Improving, adding or fixing lint suggestions

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions