Skip to content

Commit eee4f4f

Browse files
bmerryjagerman
authored andcommitted
Fix invalid memory access in vector insert method
The stl_bind.h wrapper for `Vector.insert` neglected to do a bounds check.
1 parent 6a0f6c4 commit eee4f4f

File tree

2 files changed

+5
-1
lines changed

2 files changed

+5
-1
lines changed

include/pybind11/stl_bind.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,8 @@ void vector_modifiers(enable_if_t<std::is_copy_constructible<typename Vector::va
145145

146146
cl.def("insert",
147147
[](Vector &v, SizeType i, const T &x) {
148+
if (i > v.size())
149+
throw index_error();
148150
v.insert(v.begin() + (DiffType) i, x);
149151
},
150152
arg("i") , arg("x"),

tests/test_stl_binders.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,13 @@ def test_vector_int():
1818
assert v_int != v_int2
1919

2020
v_int2.append(2)
21-
v_int2.append(3)
2221
v_int2.insert(0, 1)
2322
v_int2.insert(0, 2)
2423
v_int2.insert(0, 3)
24+
v_int2.insert(6, 3)
2525
assert str(v_int2) == "VectorInt[3, 2, 1, 0, 1, 2, 3]"
26+
with pytest.raises(IndexError):
27+
v_int2.insert(8, 4)
2628

2729
v_int.append(99)
2830
v_int2[2:-2] = v_int

0 commit comments

Comments
 (0)