Coder Social home page Coder Social logo

Comments (2)

irakliyk avatar irakliyk commented on July 27, 2024

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 vec![T::default(); length];?

from winterfell.

E-Mans-Application avatar E-Mans-Application commented on July 27, 2024

Hi,

If I understand well, the purpose of uninit_vector is to pre-allocate the vector but initialize the items later. Given that, it does not seem interesting to initialize the items with zeros (moreover, 0 may not be a valid value for the items either).

However, the current implementation is unsound. If you read documentation of set_len, you can see you break the first safety requirement: "The elements at old_len..new_len must be initialized." Moreover, you can't use res[i] = value to initialize res[i], because this reads res[i] and drops it before writing the new value. Last but not least, if anything wrong happens in the function between set_len and the initialization of the last item and causes the function to return early, the vector will be dropped and will run destructor of uninitialized items. You can notice it if you use an item type with a significant Drop implementation, such as Vec<Vec<u8>>.

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 for loop to initialize the items, you should take a look at Vec::resize_with. This does not use unsafe code at all and, on my machine, does not seem slower than methods that use unsafe code:

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:

  1. Use MaybeUninit, and use set_len after the items have been initialized.
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) };
  1. Use ptr::write, which does not read the uninitialized value, and use set_len after the items have been initialized.
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) };

from winterfell.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.