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

Get rid of mem::uninitialized() #3

Merged
merged 1 commit into from
Oct 25, 2020
Merged

Get rid of mem::uninitialized() #3

merged 1 commit into from
Oct 25, 2020

Conversation

ilaril
Copy link
Contributor

@ilaril ilaril commented Oct 24, 2020

Replace uses of mem::uninitialized() with v.reserve() + v.set_len().

mem::uninitialized() has tendency for causing UB, and recent vesions of rustc compile it to panic with many types.
The recommendation is to replace uses of mem::uninitialized() with mem::MaybeUninit. However, in this case,
since mem::uninitialized() is just used to allocate memory, it is much more straightforward to first use .reserve()
to reserve memory, then copy to vector, and then .set_len() to add the newly copied elements into vector.
This also avoids any MSRV bump, as .reseve() and .set_len() are both since 1.0 (unlike MaybeUninit, which is
since 1.36).

Closes #2

Copy link
Owner

@emilk emilk left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Beautiful fix, thank you!

@emilk emilk merged commit 28928b6 into emilk:master Oct 25, 2020
ptr::copy_nonoverlapping(value, vec.get_unchecked_mut(old_len), 1);
vec.set_len(old_len + 1);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes that is much better than mucking about with uninitialized memory. :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Heads-up: UB due to misuse of mem::uninitialized will soon lead to panic
3 participants