-
Notifications
You must be signed in to change notification settings - Fork 176
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
Safer implementation of the uninit_vector function #170
Comments
Hi! Thank you for brining this up. If I understood correctly, the above would actually initialize all the allocated memory to zeros, right? If so, what is the advantage of doing this vs. just creating a vector with initialized default elements. For example, something like |
Hi, If I understand well, the purpose of However, the current implementation is unsound. If you read documentation of For example, this crashes due to heap corruption: let mut v: Vec<Vec<u8>> = Vec::with_capacity(10);
unsafe { v.set_len(10) };
for i in 0..10 {
v[i] = vec![i as u8]; // This drops the previous value of `v[i]`, which is not initialized
} In cases where you simply use a let mut vec = Vec::new();
let mut i = 0usize;
vec.resize_with(n, || { i += 1; value_depending_on_i }); For places where the above cannot apply easily, here are some things you can do instead:
let mut vec = Vec::with_capacity(n);
let uninit_vec = vec.spare_capacity_mut();
for i in 0..n {
uninit_vec[i].write(value);
}
unsafe { vec.set_len(n) };
let mut vec: Vec<T> = Vec::with_capacity(n);
for i in 0..n {
unsafe { ptr::write(vec.as_mut_ptr().add(i), value) };
}
unsafe { vec.set_len(n) }; |
winterfell/utils/core/src/lib.rs
Lines 78 to 82 in c99530d
Hello, here's a safer implementation that uses std::mem::MaybeUninit to create an uninitialized Vec:
This implementation uses std::ptr::write_bytes to initialize each element in the vector. This ensures that all elements in the vector are properly initialized, avoiding potential memory safety issues.
The text was updated successfully, but these errors were encountered: