Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New Lint: Detect Uninitialized Vec #7681

Closed
Qwaz opened this issue Sep 17, 2021 · 2 comments · Fixed by #7682
Closed

New Lint: Detect Uninitialized Vec #7681

Qwaz opened this issue Sep 17, 2021 · 2 comments · Fixed by #7682
Assignees
Labels
A-lint Area: New lints

Comments

@Qwaz
Copy link
Contributor

Qwaz commented Sep 17, 2021

What it does

Checks for the creation of uninitialized Vec<T> by calling set_len() immediately after with_capacity() or reserve().

This is one of the most common unsound bug patterns we observed during Rudra project, e.g., bodoni/truetype#11 (RUSTSEC-2021-0029), uutils/coreutils#1729 (RUSTSEC-2021-0043).

Categories

  • Kind: Correctness

Drawbacks

For now, fixing this soundness issue might have some performance cost (if initializing a buffer) or lead to a less convenient API (if using MaybeUninit). RFC 2930 will provide a better solution once implemented.

Example

let mut vec: Vec<u8> = Vec::with_capacity(1000);
unsafe { vec.set_len(1000); }
reader.read(&mut vec); // undefined behavior!

Use an initialized buffer instead:

let mut vec: Vec<u8> = vec![0; 1000];
reader.read(&mut vec);

Or, the content can be wrapped in MaybeUninit:

let mut vec: Vec<MaybeUninit<T>> = Vec::with_capacity(1000);
unsafe { vec.set_len(1000); }
@Qwaz Qwaz added the A-lint Area: New lints label Sep 17, 2021
@Qwaz
Copy link
Contributor Author

Qwaz commented Sep 17, 2021

@rustbot claim

@ghost
Copy link

ghost commented Sep 22, 2021

Related issue: #4483

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-lint Area: New lints
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant