https://github.com/python/cpython/commit/a6495c158cbb202dcab7c19d9e5d81913847070d
commit: a6495c158cbb202dcab7c19d9e5d81913847070d
branch: 3.15
author: Miss Islington (bot) <[email protected]>
committer: JelleZijlstra <[email protected]>
date: 2026-10-20T18:32:19Z
summary:

[3.15] gh-159739: Handle OrderedDict item iterator allocation failures 
(GH-159774) (#159915)



(cherry picked from commit c8746492c580a33b2c903ac7b7ba78e43788bdd6)

Co-authored-by: Jelle Zijlstra <[email protected]>
Co-authored-by: Jelle Zijlstra <[email protected]>

files:
A Misc/NEWS.d/next/Library/2026-10-19-20-38-17.gh-issue-159739.5a6e94.rst
M Objects/odictobject.c

diff --git 
a/Misc/NEWS.d/next/Library/2026-10-19-20-38-17.gh-issue-159739.5a6e94.rst 
b/Misc/NEWS.d/next/Library/2026-10-19-20-38-17.gh-issue-159739.5a6e94.rst
new file mode 100644
index 00000000000000..e7eac98810cf48
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-10-19-20-38-17.gh-issue-159739.5a6e94.rst
@@ -0,0 +1,2 @@
+Avoid a crash when memory allocation fails while creating a
+:class:`collections.OrderedDict` items iterator.
diff --git a/Objects/odictobject.c b/Objects/odictobject.c
index 6f10c4863856d9..247cee98a16f10 100644
--- a/Objects/odictobject.c
+++ b/Objects/odictobject.c
@@ -1941,22 +1941,21 @@ odictiter_new(PyODictObject *od, int kind)
     odictiterobject *di;
     _ODictNode *node;
     int reversed = kind & _odict_ITER_REVERSED;
-
-    di = PyObject_GC_New(odictiterobject, &PyODictIter_Type);
-    if (di == NULL)
-        return NULL;
+    PyObject *result = NULL;
 
     if ((kind & _odict_ITER_ITEMS) == _odict_ITER_ITEMS) {
-        di->di_result = _PyTuple_FromPairSteal(Py_None, Py_None);
-        if (di->di_result == NULL) {
-            Py_DECREF(di);
+        result = _PyTuple_FromPairSteal(Py_None, Py_None);
+        if (result == NULL) {
             return NULL;
         }
     }
-    else {
-        di->di_result = NULL;
+    di = PyObject_GC_New(odictiterobject, &PyODictIter_Type);
+    if (di == NULL) {
+        Py_XDECREF(result);
+        return NULL;
     }
 
+    di->di_result = result;
     di->kind = kind;
     node = reversed ? _odict_LAST(od) : _odict_FIRST(od);
     di->di_current = node ? Py_NewRef(_odictnode_KEY(node)) : NULL;

_______________________________________________
Python-checkins mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3//lists/python-checkins.python.org
Member address: [email protected]

Reply via email to