Skip to content

Commit 05db290

Browse files
committed
Fix list_new_prealloc() integer overflow check
Use again PyMem_New() since it checks for overflow. Also, initialize "op->ob_item = NULL;" if list_allocate_array() fails.
1 parent 42190b8 commit 05db290

2 files changed

Lines changed: 8 additions & 1 deletion

File tree

‎Lib/test/test_capi/test_list.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -381,6 +381,12 @@ def create_items(self, nitem):
381381
# which are immortal (and so would not check for reference leaks).
382382
return tuple(object() for i in range(nitem))
383383

384+
def test_create_overflow(self):
385+
# Test PyListBuilder_Create() check for integer overflow
386+
max_nitem = sys.maxsize // _testcapi.SIZEOF_VOID_P
387+
self.assertRaises(MemoryError, self.create_builder, max_nitem + 1)
388+
self.assertRaises(MemoryError, self.create_builder, sys.maxsize)
389+
384390
def check_append(self, method):
385391
items = self.create_items(3)
386392
for size in (0, len(items), len(items) * 10):

‎Objects/listobject.c‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -327,12 +327,13 @@ list_new_prealloc(Py_ssize_t size)
327327
#ifdef Py_GIL_DISABLED
328328
_PyListArray *array = list_allocate_array(size);
329329
if (array == NULL) {
330+
op->ob_item = NULL;
330331
Py_DECREF(op);
331332
return PyErr_NoMemory();
332333
}
333334
op->ob_item = array->ob_item;
334335
#else
335-
op->ob_item = (PyObject **) PyMem_Malloc(size * sizeof(PyObject *));
336+
op->ob_item = PyMem_New(PyObject *, size);
336337
if (op->ob_item == NULL) {
337338
Py_DECREF(op);
338339
return PyErr_NoMemory();

0 commit comments

Comments
 (0)