diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-07-18-22-56-27.gh-issue-152125.sEPvJf.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-07-18-22-56-27.gh-issue-152125.sEPvJf.rst new file mode 100644 index 00000000000000..ae66f69f206217 --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-07-18-22-56-27.gh-issue-152125.sEPvJf.rst @@ -0,0 +1,3 @@ +Fix a crash in the :term:`free-threaded build` where :c:func:`PyList_New` could leave +a newly allocated list's item buffer pointer uninitialized when the backing +array allocation failed under low memory, leading to an invalid free. diff --git a/Objects/listobject.c b/Objects/listobject.c index 8a9c9bda68269b..04db98bc28a5c8 100644 --- a/Objects/listobject.c +++ b/Objects/listobject.c @@ -252,10 +252,11 @@ PyList_New(Py_ssize_t size) return NULL; } } - if (size <= 0) { - op->ob_item = NULL; - } - else { + op->ob_item = NULL; + Py_SET_SIZE(op, size); + op->allocated = size; + + if (size > 0) { #ifdef Py_GIL_DISABLED _PyListArray *array = list_allocate_array(size); if (array == NULL) { @@ -272,8 +273,6 @@ PyList_New(Py_ssize_t size) return PyErr_NoMemory(); } } - Py_SET_SIZE(op, size); - op->allocated = size; _PyObject_GC_TRACK(op); return (PyObject *) op; }