Skip to content

Commit ba04abb

Browse files
committed
Fix PyListBuilder_ExtendArraySteal()
Always clear the array on error. Previously, only one error path was covered: two code paths didn't clear the array. Update PyListBuilder_ExtendArray(): mention that nitem must not be negative.
1 parent 297af71 commit ba04abb

2 files changed

Lines changed: 11 additions & 7 deletions

File tree

‎Doc/c-api/list.rst‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -314,6 +314,8 @@ On Free Threading, it's more efficient than the ``PyList`` C API to create a
314314
On success, return ``0``.
315315
On error, set an exception, leave the builder unchanged, and return ``-1``.
316316
317+
*nitem* must not be negative.
318+
317319
If resizing the builder fails (memory allocation failure), the builder is
318320
restored to its previous state: discard added items.
319321

‎Objects/listobject.c‎

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4676,7 +4676,8 @@ PyListBuilder_Extend(PyListBuilder *builder, PyObject *iterable)
46764676
}
46774677

46784678

4679-
// Force inlining to optimize "if (steal)" at build time
4679+
// Force inlining to optimize "if (steal)" at build time.
4680+
// On error if steal is non-zero, the caller must clear the array.
46804681
static inline Py_ALWAYS_INLINE int
46814682
listbuilder_extend_array(PyListBuilder *builder,
46824683
PyObject *const *items, Py_ssize_t nitem,
@@ -4711,11 +4712,6 @@ listbuilder_extend_array(PyListBuilder *builder,
47114712
Py_ssize_t new_size = old_size + nitem;
47124713
if (new_size > list->allocated) {
47134714
if (listbuilder_resize(builder, new_size) < 0) {
4714-
if (steal) {
4715-
for (Py_ssize_t i = 0; i < nitem; i++) {
4716-
Py_DECREF(items[i]);
4717-
}
4718-
}
47194715
return -1;
47204716
}
47214717
}
@@ -4748,5 +4744,11 @@ int
47484744
PyListBuilder_ExtendArraySteal(PyListBuilder *builder,
47494745
PyObject *const *items, Py_ssize_t nitem)
47504746
{
4751-
return listbuilder_extend_array(builder, items, nitem, 1);
4747+
int res = listbuilder_extend_array(builder, items, nitem, 1);
4748+
if (res < 0) {
4749+
for (Py_ssize_t index = 0; index < nitem; index++) {
4750+
Py_DECREF(items[index]);
4751+
}
4752+
}
4753+
return res;
47524754
}

0 commit comments

Comments
 (0)