Skip to content

gh-146152: Fix memory leak in _json encoder error paths#146164

Open
okiemute04 wants to merge 1 commit intopython:mainfrom
okiemute04:fix-json-encoder-leak
Open

gh-146152: Fix memory leak in _json encoder error paths#146164
okiemute04 wants to merge 1 commit intopython:mainfrom
okiemute04:fix-json-encoder-leak

Conversation

@okiemute04
Copy link
Contributor

@okiemute04 okiemute04 commented Mar 19, 2026

Fixes #146152

Add PyDict_DelItem calls to remove objects from the markers dict
on all error paths in encoder_listencode_obj. Previously, objects
were only removed on the success path, causing memory leaks when:

  • default() raises an exception
  • RecursionError occurs
  • Nested encoding fails

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.
@okiemute04 okiemute04 force-pushed the fix-json-encoder-leak branch from 51c39f9 to 0597100 Compare March 19, 2026 14:00
Copy link
Member

@serhiy-storchaka serhiy-storchaka left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am not sure that this works. Please add a test.

  • Define default() which creates a new object, adds a weak reference to it to the list, and returns that object.
  • Call JSON encoding, and after catching an exception, call test.support.gc_collect(), then test that all weak references in the list return None.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

_json: stale markers entries on error paths in encoder_listencode_obj

2 participants