Skip to content

Commit e00e2ef

Browse files
committed
Fix a memory safety bug in SmallVec::grow
1 parent 392fb2e commit e00e2ef

File tree

1 file changed

+12
-0
lines changed

1 file changed

+12
-0
lines changed

lib.rs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -301,7 +301,11 @@ impl<A: Array> SmallVec<A> {
301301
}
302302
}
303303

304+
/// Re-allocate to set the capacity to `new_cap`.
305+
///
306+
/// Panics if `new_cap` is less than the vector's length.
304307
pub fn grow(&mut self, new_cap: usize) {
308+
assert!(new_cap >= self.len);
305309
let mut vec: Vec<A::Item> = Vec::with_capacity(new_cap);
306310
let new_alloc = vec.as_mut_ptr();
307311
unsafe {
@@ -967,6 +971,14 @@ pub mod tests {
967971
assert_eq!(&v.iter().map(|v| **v).collect::<Vec<_>>(), &[0, 3, 2]);
968972
}
969973

974+
#[test]
975+
#[should_panic]
976+
fn test_invalid_grow() {
977+
let mut v: SmallVec<[u8; 8]> = SmallVec::new();
978+
v.extend(0..8);
979+
v.grow(5);
980+
}
981+
970982
#[test]
971983
#[should_panic]
972984
fn test_drop_panic_smallvec() {

0 commit comments

Comments
 (0)