Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

segfault when casting dictionary with circular reference to nlohmann::json #73

Closed
dbaston opened this issue Dec 6, 2024 · 1 comment · Fixed by #74
Closed

segfault when casting dictionary with circular reference to nlohmann::json #73

dbaston opened this issue Dec 6, 2024 · 1 comment · Fixed by #74
Labels
bug Something isn't working

Comments

@dbaston
Copy link
Contributor

dbaston commented Dec 6, 2024

Demonstrated by the following test case:

TEST(pybind11_caster_tojson, recursive_dict)
{
    py::scoped_interpreter guard;
    py::module m = create_module("test");

    m.def("to_json", &test_fromtojson);

    // Simulate calling this binding from Python with a dictionary as argument
    py::dict obj("number"_a=1234, "hello"_a="world");
    obj["recur"] = obj;
    py::print(obj); // ok

    nl::json j = m.attr("to_json")(obj); // segfault
}

This situation is detected by the json module:

>>> obj = {"number": 1234, "hello" : "world"}
>>> obj["recur"] = obj
>>> json.dumps(obj)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.10/json/__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)
  File "/usr/lib/python3.10/json/encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/usr/lib/python3.10/json/encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
ValueError: Circular reference detected
@martinRenou
Copy link
Collaborator

Thanks for opening an issue!

Any help in fixing it would be very much appreciated

@martinRenou martinRenou added the bug Something isn't working label Dec 6, 2024
dbaston added a commit to dbaston/pybind11_json that referenced this issue Dec 6, 2024
dbaston added a commit to dbaston/pybind11_json that referenced this issue Dec 6, 2024
dbaston added a commit to dbaston/pybind11_json that referenced this issue Dec 9, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants