Skip to content

Commit 0597100

Browse files
committed
gh-146152: Fix memory leak in _json encoder recursion path
Only clean up markers on the RecursionError path (PATH B), where objects accumulate during stack unwinding. Other error paths are safe because the markers dict is local and will be freed. Based on review feedback from @raminfp and @serhiy-storchaka.
1 parent 91e1312 commit 0597100

File tree

2 files changed

+9
-1
lines changed

2 files changed

+9
-1
lines changed
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fix a memory leak in the :mod:`json` module when encoding objects with a
2+
custom ``default()`` function that raises an exception, when a recursion
3+
error occurs, or when nested encoding fails.

Modules/_json.c

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1632,8 +1632,12 @@ encoder_listencode_obj(PyEncoderObject *s, PyUnicodeWriter *writer,
16321632
}
16331633

16341634
if (_Py_EnterRecursiveCall(" while encoding a JSON object")) {
1635+
if (ident != NULL) {
1636+
PyDict_DelItem(s->markers, ident);
1637+
Py_XDECREF(ident);
1638+
}
16351639
Py_DECREF(newobj);
1636-
Py_XDECREF(ident);
1640+
16371641
return -1;
16381642
}
16391643
rv = encoder_listencode_obj(s, writer, newobj, indent_level, indent_cache);
@@ -1642,6 +1646,7 @@ encoder_listencode_obj(PyEncoderObject *s, PyUnicodeWriter *writer,
16421646
Py_DECREF(newobj);
16431647
if (rv) {
16441648
_PyErr_FormatNote("when serializing %T object", obj);
1649+
16451650
Py_XDECREF(ident);
16461651
return -1;
16471652
}

0 commit comments

Comments
 (0)