From 495b40c534e63cc49d64e8369cb726b3ec88d7c3 Mon Sep 17 00:00:00 2001 From: Charalampos Stratakis Date: Fri, 20 Feb 2026 16:58:28 +0100 Subject: [PATCH] Free xmlDoc on initDocDict failure in _newXMLDoc/_newHTMLDoc If __GLOBAL_PARSER_CONTEXT.initDocDict() raises an exception after xmlNewDoc()/htmlNewDoc() has already allocated the document, the error path never frees it. --- src/lxml/parser.pxi | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/lxml/parser.pxi b/src/lxml/parser.pxi index 8d53277..43e6476 100644 --- a/src/lxml/parser.pxi +++ b/src/lxml/parser.pxi @@ -1972,7 +1972,11 @@ cdef xmlDoc* _newXMLDoc() except NULL: raise MemoryError() if result.encoding is NULL: result.encoding = tree.xmlStrdup("UTF-8") - __GLOBAL_PARSER_CONTEXT.initDocDict(result) + try: + __GLOBAL_PARSER_CONTEXT.initDocDict(result) + except: + tree.xmlFreeDoc(result) + raise return result cdef xmlDoc* _newHTMLDoc() except NULL: @@ -1980,7 +1984,11 @@ cdef xmlDoc* _newHTMLDoc() except NULL: result = tree.htmlNewDoc(NULL, NULL) if result is NULL: raise MemoryError() - __GLOBAL_PARSER_CONTEXT.initDocDict(result) + try: + __GLOBAL_PARSER_CONTEXT.initDocDict(result) + except: + tree.xmlFreeDoc(result) + raise return result cdef xmlDoc* _copyDoc(xmlDoc* c_doc, int recursive) except NULL: -- 2.53.0