From 54c73d2db59cc2a283f4dadc8b1e1da9901e8c08 Mon Sep 17 00:00:00 2001 From: Timur Mamedov Date: Wed, 24 Jun 2026 15:40:29 -0400 Subject: [PATCH] gh-148731: Fix crash in Element.iter() on allocation failure Initialize parent_stack and parent_stack_used before the fallible PyMem_New call so that elementiter_dealloc does not dereference an uninitialized pointer when the allocation fails. --- .../Library/2026-06-24-12-00-00.gh-issue-148731.ElItOm.rst | 2 ++ Modules/_elementtree.c | 4 +++- 2 files changed, 5 insertions(+), 1 deletion(-) create mode 100644 Misc/NEWS.d/next/Library/2026-06-24-12-00-00.gh-issue-148731.ElItOm.rst diff --git a/Misc/NEWS.d/next/Library/2026-06-24-12-00-00.gh-issue-148731.ElItOm.rst b/Misc/NEWS.d/next/Library/2026-06-24-12-00-00.gh-issue-148731.ElItOm.rst new file mode 100644 index 000000000000000..b01bf1ab3af0e34 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-06-24-12-00-00.gh-issue-148731.ElItOm.rst @@ -0,0 +1,2 @@ +Fix crash in :meth:`xml.etree.ElementTree.Element.iter` when memory +allocation fails during iterator construction. diff --git a/Modules/_elementtree.c b/Modules/_elementtree.c index f827274eeffba83..127b1fed3063806 100644 --- a/Modules/_elementtree.c +++ b/Modules/_elementtree.c @@ -2368,6 +2368,9 @@ create_elementiter(elementtreestate *st, ElementObject *self, PyObject *tag, if (!it) return NULL; + it->parent_stack = NULL; + it->parent_stack_used = 0; + it->sought_tag = Py_NewRef(tag); it->gettext = gettext; it->root_element = (ElementObject*)Py_NewRef(self); @@ -2378,7 +2381,6 @@ create_elementiter(elementtreestate *st, ElementObject *self, PyObject *tag, PyErr_NoMemory(); return NULL; } - it->parent_stack_used = 0; it->parent_stack_size = INIT_PARENT_STACK_SIZE; PyObject_GC_Track(it);