Skip to content

Commit 4dade05

Browse files
authored
gh-128961: Fix exhausted array iterator crash in __setstate__() (#128962)
1 parent 9ed7bf2 commit 4dade05

File tree

3 files changed

+19
-5
lines changed

3 files changed

+19
-5
lines changed

Lib/test/test_array.py

+8
Original file line numberDiff line numberDiff line change
@@ -1665,5 +1665,13 @@ def test_tolist(self, size):
16651665
self.assertEqual(ls[:8], list(example[:8]))
16661666
self.assertEqual(ls[-8:], list(example[-8:]))
16671667

1668+
def test_gh_128961(self):
1669+
a = array.array('i')
1670+
it = iter(a)
1671+
list(it)
1672+
it.__setstate__(0)
1673+
self.assertRaises(StopIteration, next, it)
1674+
1675+
16681676
if __name__ == "__main__":
16691677
unittest.main()
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix a crash when setting state on an exhausted :class:`array.array` iterator.

Modules/arraymodule.c

+10-5
Original file line numberDiff line numberDiff line change
@@ -3090,11 +3090,16 @@ array_arrayiterator___setstate__(arrayiterobject *self, PyObject *state)
30903090
Py_ssize_t index = PyLong_AsSsize_t(state);
30913091
if (index == -1 && PyErr_Occurred())
30923092
return NULL;
3093-
if (index < 0)
3094-
index = 0;
3095-
else if (index > Py_SIZE(self->ao))
3096-
index = Py_SIZE(self->ao); /* iterator exhausted */
3097-
self->index = index;
3093+
arrayobject *ao = self->ao;
3094+
if (ao != NULL) {
3095+
if (index < 0) {
3096+
index = 0;
3097+
}
3098+
else if (index > Py_SIZE(ao)) {
3099+
index = Py_SIZE(ao); /* iterator exhausted */
3100+
}
3101+
self->index = index;
3102+
}
30983103
Py_RETURN_NONE;
30993104
}
31003105

0 commit comments

Comments
 (0)