10000 PyList_GET_ITEM() now checks the index · python/cpython@255edc3 · GitHub
[go: up one dir, main page]

Skip to content

Commit 255edc3

Browse files
committed
PyList_GET_ITEM() now checks the index
1 parent 6b5166f commit 255edc3

File tree

4 files changed

+12
-3
lines changed

4 files changed

+12
-3
lines changed

Doc/whatsnew/3.13.rst

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -441,6 +441,12 @@ New Features
441441
``NULL`` if the referent is no longer live.
442442
(Contributed by Victor Stinner in :gh:`105927`.)
443443

444+
* In debug mode and on :option:`Python built with assertions <--with-assertions>`,
445+
:c:func:`PyList_GET_ITEM` now checks the index with an assertion.
446+
If the assertion fails, make sure that the list size is set before calling
447+
:c:func:`PyList_GET_ITEM`.
448+
(Contributed by Victor Stinner.)
449+
444450
Porting to Python 3.13
445451
----------------------
446452

Include/cpython/listobject.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,8 @@ static inline Py_ssize_t PyList_GET_SIZE(PyObject *op) {
4141
static inline void
4242
PyList_SET_ITEM(PyObject *op, Py_ssize_t index, PyObject *value) {
4343
PyListObject *list = _PyList_CAST(op);
44+
assert(0 <= index);
45+
assert(index < Py_SIZE(list));
4446
list->ob_item[index] = value;
4547
}
4648
#define PyList_SET_ITEM(op, index, value) \

Include/internal/pycore_list.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,8 +49,8 @@ _PyList_AppendTakeRef(PyListObject *self, PyObject *newitem)
4949
Py_ssize_t allocated = self->allocated;
5050
assert((size_t)len + 1 < PY_SSIZE_T_MAX);
5151
if (allocated > len) {
52-
PyList_SET_ITEM(self, len, newitem);
5352
Py_SET_SIZE(self, len + 1);
53+
PyList_SET_ITEM(self, len, newitem);
5454
return 0;
5555
}
5656
return _PyList_AppendTakeRefListResize(self, newitem);

Objects/listobject.c

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -953,8 +953,9 @@ list_extend(PyListObject *self, PyObject *iterable)
953953
}
954954
if (Py_SIZE(self) < self->allocated) {
955955
/* steals ref */
956-
PyList_SET_ITEM(self, Py_SIZE(self), item);
957-
Py_SET_SIZE(self, Py_SIZE(self) + 1);
956+
Py_ssize_t len = Py_SIZE(self);
957+
Py_SET_SIZE(self, len + 1);
958+
PyList_SET_ITEM(self, len, item);
958959
}
959960
else {
960961
if (_PyList_AppendTakeRef(self, item) < 0)

0 commit comments

Comments
 (0)
0