Closed
Description
The safety clause on the Vec::set_len
function says that:
- new_len must be less than or equal to capacity().
- The elements at old_len..new_len must be initialized.
However, the code example for std::ptr::copy
violates the second rule
use std::ptr;
unsafe fn from_buf_raw<T>(ptr: *const T, elts: usize) -> Vec<T> {
let mut dst = Vec::with_capacity(elts);
dst.set_len(elts);
ptr::copy(ptr, dst.as_mut_ptr(), elts);
dst
}
The set_len
is called before the values are initialized with the copy.
This could be fixed by either making the safety clause for set_len
more inclusive, so that as long as you don't use the vector before initializing the values it's considered safe, or by switching the dst.set_len(elts);
and ptr::copy(ptr, dst.as_mut_ptr(), alts);
lines around in the example.