about summary refs log tree commit diff
diff options
context:
space:
mode:
authorbors <bors@rust-lang.org>2024-03-20 21:37:30 +0000
committerbors <bors@rust-lang.org>2024-03-20 21:37:30 +0000
commit1388d7a069d872bcfe5e5dd97ef61fa0a586fac0 (patch)
tree80ad5cb88d9412ddc947a26adbc72038a49dbe8f
parente3df96cfda905301fc8514e000f942222c1ab6ad (diff)
parent37718f949fe5bef4bbfa4ee393c2abf022771ccb (diff)
downloadrust-1388d7a069d872bcfe5e5dd97ef61fa0a586fac0.tar.gz
rust-1388d7a069d872bcfe5e5dd97ef61fa0a586fac0.zip
Auto merge of #122761 - jwong101:fix/vec-insert, r=workingjubilee,Nilstrieb
fix OOB pointer formed in Vec::index

Move the length check to before using `index` with `ptr::add` to prevent an out of bounds pointer from being formed.

Fixes #122760
-rw-r--r--library/alloc/src/vec/mod.rs7
1 files changed, 3 insertions, 4 deletions
diff --git a/library/alloc/src/vec/mod.rs b/library/alloc/src/vec/mod.rs
index db56b8d07c7..94bed825bb2 100644
--- a/library/alloc/src/vec/mod.rs
+++ b/library/alloc/src/vec/mod.rs
@@ -1541,6 +1541,9 @@ impl<T, A: Allocator> Vec<T, A> {
         }
 
         let len = self.len();
+        if index > len {
+            assert_failed(index, len);
+        }
 
         // space for the new element
         if len == self.buf.capacity() {
@@ -1556,10 +1559,6 @@ impl<T, A: Allocator> Vec<T, A> {
                     // Shift everything over to make space. (Duplicating the
                     // `index`th element into two consecutive places.)
                     ptr::copy(p, p.add(1), len - index);
-                } else if index == len {
-                    // No elements need shifting.
-                } else {
-                    assert_failed(index, len);
                 }
                 // Write it in, overwriting the first copy of the `index`th
                 // element.