Skip to content

Commit 9370f4f

Browse files
committed
gh-146250: Fix memory leak of re-initialization of SyntaxError
Added `Py_XDECREF`/`Py_XSETREF` to avoid a memory leak when calling `SyntaxError.__init__`.
1 parent 879c85f commit 9370f4f

File tree

2 files changed

+14
-2
lines changed

2 files changed

+14
-2
lines changed

Lib/test/test_exceptions.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1954,6 +1954,12 @@ def test_exec_set_nomemory_hang(self):
19541954
self.assertGreater(len(output), 0) # At minimum, should not hang
19551955
self.assertIn(b"MemoryError", output)
19561956

1957+
# gh-146250: memory leak with re-initialization of SyntaxError
1958+
def test_syntax_error_memory_leak(self):
1959+
# Test crashes with ASan
1960+
e = SyntaxError("msg", ("file.py", 1, 2, "txt", 2, 3))
1961+
e.__init__("new_msg", ("new_file.py", 2, 3, "new_txt", 3, 4))
1962+
19571963

19581964
class NameErrorTests(unittest.TestCase):
19591965
def test_name_error_has_name(self):

Objects/exceptions.c

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2802,8 +2802,14 @@ SyntaxError_init(PyObject *op, PyObject *args, PyObject *kwds)
28022802
return -1;
28032803
}
28042804

2805-
self->end_lineno = NULL;
2806-
self->end_offset = NULL;
2805+
Py_XDECREF(self->filename);
2806+
Py_XDECREF(self->lineno);
2807+
Py_XDECREF(self->offset);
2808+
Py_XDECREF(self->text);
2809+
Py_XSETREF(self->end_lineno, NULL);
2810+
Py_XSETREF(self->end_offset, NULL);
2811+
Py_XDECREF(self->metadata);
2812+
28072813
if (!PyArg_ParseTuple(info, "OOOO|OOO",
28082814
&self->filename, &self->lineno,
28092815
&self->offset, &self->text,

0 commit comments

Comments
 (0)