Skip to content

extend_from_within leaks elements on panic #82533

Closed
@cmazakas

Description

@cmazakas

impl<T: Clone, A: Allocator> ExtendFromWithinSpec for Vec<T, A> {
default unsafe fn spec_extend_from_within(&mut self, src: Range<usize>) {
let initialized = {
let (this, spare) = self.split_at_spare_mut();
// Safety:
// - caller guaratees that src is a valid index
let to_clone = unsafe { this.get_unchecked(src) };
to_clone.iter().cloned().zip(spare.iter_mut()).map(|(e, s)| s.write(e)).count()
};
// Safety:
// - elements were just initialized
unsafe {
let new_len = self.len() + initialized;
self.set_len(new_len);
}
}
}

Looking here, the internal length of the vector is only adjusted at the end of the loop

This has the caveat that if cloning panics, the Vec will start to unwind and only drop the first len elements which doesn't include the most recently appended ones.

Something more in line with how the stdlib does things might look like this:
https://github.com/LeonineKing1199/minivec/blob/424354dfababae7101aacf70fa9332a87e9cdb15/src/lib.rs#L1612-L1700

Metadata

Metadata

Assignees

Labels

C-bugCategory: This is a bug.P-mediumMedium priorityT-libsRelevant to the library team, which will review and decide on the PR/issue.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions