Closed krishna116 closed 2 years ago
It's all explained in the docs: https://jansson.readthedocs.io/en/latest/apiref.html#reference-count
In a nutshell: If you create a new JSON value, you must call json_decref()
to release your reference to it. If you use a function that steals the reference (these functions end with _new
), you must not call json_decref()
anymore.
In your example, these references are leaked:
json_t* kv = json_object();
. Fix: use json_array_append_new()
json_string("value4")
. Fix: use json_object_set_new()
It is a interesting design, I have traced the reference count, if I use json_array_append(root, kv), the kv's reference count will increase to 2, if I use json_array_append_new(root, kv), the kv's reference count will stay at 1, thank you for the explain, I think I understand it now.
Now I am learning how to using this jansson library, I'm not very clear about the memory management in this library, so I write a small test to test my idea and I found memory leak, this is my test code:
// using visual studio 2019, console application(x86). // using jansson-version: 2.13.1
and there are some APIs I don't very clear, for example: json_object_set(json_t object, const char key, json_t *value) question: if (json_object_set ok), the key buffer will attached to the object tree and key's life time is managed by the object? if (json_object_set fail), the key buffer is managed by caller? if (json_object_set ok), the value buffer will attached to the object tree and value buffer's life time is managed by the object? if (json_object_set fail), the value buffer is managed by caller?
can sombody explain?
thank you!