diff --git a/Lib/test/test_syntax.py b/Lib/test/test_syntax.py index b035883cf883b93..9accbd0c07d7989 100644 --- a/Lib/test/test_syntax.py +++ b/Lib/test/test_syntax.py @@ -2244,6 +2244,7 @@ def f(x: *b) import unittest from test import support +from test.support.script_helper import assert_python_ok class SyntaxTestCase(unittest.TestCase): @@ -2496,6 +2497,22 @@ class A: class B[{name}]: pass """, "", mode="exec") + @support.nomemtest + def test_disallowed_type_param_names_oom(self): + # gh-152682: Don't crash on OOM when formatting the SyntaxError message + # in symtable_visit_type_param_bound_or_default. + code = textwrap.dedent("""\ + import _testcapi + _testcapi.set_nomemory(0) + try: + compile("class A[__classdict__]: pass", "", "exec") + except MemoryError: + pass + else: + raise RuntimeError('MemoryError not raised') + """) + assert_python_ok("-c", code) + @support.cpython_only def test_nested_named_except_blocks(self): code = "" diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-30-14-00-00.gh-issue-152682.yId7e5.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-06-30-14-00-00.gh-issue-152682.yId7e5.rst new file mode 100644 index 000000000000000..aba0b594382bcf8 --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-06-30-14-00-00.gh-issue-152682.yId7e5.rst @@ -0,0 +1,3 @@ +Fix NULL pointer dereference in :func:`compile` when a reserved name (e.g. +``__classdict__``) is used as a type parameter name and memory allocation +fails while formatting the error message. diff --git a/Python/symtable.c b/Python/symtable.c index f60af2b6955d71c..ece994cf0910cbc 100644 --- a/Python/symtable.c +++ b/Python/symtable.c @@ -2318,6 +2318,9 @@ symtable_visit_type_param_bound_or_default( PyObject *error_msg = PyUnicode_FromFormat("reserved name '%U' cannot be " "used for type parameter", name); + if (error_msg == NULL) { + return 0; + } PyErr_SetObject(PyExc_SyntaxError, error_msg); Py_DECREF(error_msg); PyErr_RangedSyntaxLocationObject(st->st_filename,