Closed
Description
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); }