From 4e5f82c5a586f93294af570996fc33ba8649d9d3 Mon Sep 17 00:00:00 2001 From: Sam Gross Date: Fri, 12 Jul 2024 19:17:22 +0000 Subject: [PATCH] gh-121652: Handle `allocate_weakref` returning NULL The `allocate_weakref` may return NULL when out of memory. We need to handle that case and propagate the error. --- Objects/weakrefobject.c | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/Objects/weakrefobject.c b/Objects/weakrefobject.c index 0fcd37d949b34a..61f05514a48023 100644 --- a/Objects/weakrefobject.c +++ b/Objects/weakrefobject.c @@ -426,6 +426,10 @@ get_or_create_weakref(PyTypeObject *type, PyObject *obj, PyObject *callback) return basic_ref; } PyWeakReference *newref = allocate_weakref(type, obj, callback); + if (newref == NULL) { + UNLOCK_WEAKREFS(obj); + return NULL; + } insert_weakref(newref, list); UNLOCK_WEAKREFS(obj); return newref; @@ -433,6 +437,9 @@ get_or_create_weakref(PyTypeObject *type, PyObject *obj, PyObject *callback) else { // We may not be able to safely allocate inside the lock PyWeakReference *newref = allocate_weakref(type, obj, callback); + if (newref == NULL) { + return NULL; + } LOCK_WEAKREFS(obj); insert_weakref(newref, list); UNLOCK_WEAKREFS(obj);