Skip to content

Fix a leak in RawJSON() when the argument is rejected - #239

Merged
lelit merged 1 commit into
python-rapidjson:masterfrom
espressolee:rawjson-new-leak
Sep 5, 2026
Merged

lelit merged 1 commit into
python-rapidjson:masterfrom
espressolee:rawjson-new-leak

Conversation

@espressolee

Copy link
Copy Markdown
Contributor

RawJSON(value) leaks one object every time the argument is rejected: RawJSON_new calls tp_alloc before PyArg_ParseTupleAndKeywords, and the failure branch returns NULL without releasing it. The result of tp_alloc was also never checked.

This reorders the constructor to parse first and allocate second, matching decoder_new / encoder_new / validator_new, and adds a tracemalloc test next to the existing ones in test_memory_leaks.py. On CPython 3.12.13, 100,000 rejected calls increased sys.getallocatedblocks() by 100,001 before this change and by 1 after; the 1.23 source I measured has the same RawJSON_new as master.

Also fixes the stub, where RawJSON.value was typed as RawJSON instead of str. That hunk is independent; drop it if you would rather not have it here.

Assisted-by: Claude Code:claude-fable-5-1

RawJSON_new allocated the object before parsing its argument and
returned NULL without releasing it when the "U" check failed, so every
RawJSON(<non-str>) leaked one object. Parse first and allocate second,
as the other constructors in this file do, and check tp_alloc's result.
Add a tracemalloc test in the shape of the existing ones: 1000 rejected
calls leave 1001 extra allocations before this change and 0 after.

Also fix the stub: RawJSON.value is the str that was passed, not a
RawJSON.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@lelit

lelit commented Sep 4, 2026

Copy link
Copy Markdown
Contributor

Thank you, will merge before next release.

@lelit
lelit merged commit cb14886 into python-rapidjson:master Sep 5, 2026
9 checks passed
@lelit

lelit commented Sep 5, 2026

Copy link
Copy Markdown
Contributor

Merged in just released v1.24.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants