Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Fix a leak in RawJSON() when the argument is rejected
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 <noreply@anthropic.com>
  • Loading branch information
espressolee and claude committed Sep 3, 2026
commit 123396b10fd456c5d6585e98c3ef53f8d385459b
5 changes: 4 additions & 1 deletion rapidjson.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -465,7 +465,6 @@ RawJSON_dealloc(RawJSON* self)
static PyObject*
RawJSON_new(PyTypeObject* type, PyObject* args, PyObject* kwds)
{
PyObject* self = type->tp_alloc(type, 0);
static char const* kwlist[] = {
"value",
NULL
Expand All @@ -475,6 +474,10 @@ RawJSON_new(PyTypeObject* type, PyObject* args, PyObject* kwds)
if (!PyArg_ParseTupleAndKeywords(args, kwds, "U", (char**) kwlist, &value))
return NULL;

PyObject* self = type->tp_alloc(type, 0);
if (self == NULL)
return NULL;

((RawJSON*) self)->value = value;

Py_INCREF(value);
Expand Down
27 changes: 27 additions & 0 deletions tests/test_memory_leaks.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,3 +125,30 @@ def test_failed_validation():
for stat in top_stats[:10]:
# Uhm, with Py 3.14, on macOS, the diff is 3...
assert stat.count_diff <= 3


def test_rejected_rawjson_value():
tracemalloc.start()

snapshot1 = tracemalloc.take_snapshot().filter_traces((
tracemalloc.Filter(True, __file__),))

# start the test
for j in range(1000):
try:
rj.RawJSON(j)
except TypeError:
pass

del j

gc.collect()

snapshot2 = tracemalloc.take_snapshot().filter_traces((
tracemalloc.Filter(True, __file__),))

top_stats = snapshot2.compare_to(snapshot1, 'lineno')
tracemalloc.stop()

for stat in top_stats[:10]:
assert stat.count_diff <= 3
2 changes: 1 addition & 1 deletion typings/rapidjson/__init__.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ class Encoder:

@t.final
class RawJSON:
value: RawJSON
value: str
def __new__(cls, value: str) -> RawJSON: ...


Expand Down