From dab738dec4b787d73198c19bae08b1f0cb46c350 Mon Sep 17 00:00:00 2001 From: Steve Stagg Date: Mon, 6 Jul 2026 11:28:17 +0100 Subject: [PATCH] gh-153182: Explicitly return NULL when `new_keys_object` call fails in `_PyDict_NewKeysForClass` to prevent a segfault when subsequent code tries to use the returned object --- .../2026-07-06-11-22-58.gh-issue-153182.pHqb1F.rst | 1 + Objects/dictobject.c | 11 +++++------ 2 files changed, 6 insertions(+), 6 deletions(-) create mode 100644 Misc/NEWS.d/next/Core_and_Builtins/2026-07-06-11-22-58.gh-issue-153182.pHqb1F.rst diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-07-06-11-22-58.gh-issue-153182.pHqb1F.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-07-06-11-22-58.gh-issue-153182.pHqb1F.rst new file mode 100644 index 000000000000000..68906f7477a70af --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-07-06-11-22-58.gh-issue-153182.pHqb1F.rst @@ -0,0 +1 @@ +Fix a crash when defining a class in low memory conditions. diff --git a/Objects/dictobject.c b/Objects/dictobject.c index 6029205eac8b20f..09c98401cd11a9b 100644 --- a/Objects/dictobject.c +++ b/Objects/dictobject.c @@ -7219,13 +7219,12 @@ _PyDict_NewKeysForClass(PyHeapTypeObject *cls) PyDictKeysObject *keys = new_keys_object(NEXT_LOG2_SHARED_KEYS_MAX_SIZE, 1); if (keys == NULL) { PyErr_Clear(); + return NULL; } - else { - assert(keys->dk_nentries == 0); - /* Set to max size+1 as it will shrink by one before each new object */ - keys->dk_usable = SHARED_KEYS_MAX_SIZE; - keys->dk_kind = DICT_KEYS_SPLIT; - } + assert(keys->dk_nentries == 0); + /* Set to max size+1 as it will shrink by one before each new object */ + keys->dk_usable = SHARED_KEYS_MAX_SIZE; + keys->dk_kind = DICT_KEYS_SPLIT; if (cls->ht_type.tp_dict) { PyObject *attrs = PyDict_GetItem(cls->ht_type.tp_dict, &_Py_ID(__static_attributes__)); if (attrs != NULL && PyTuple_Check(attrs)) {