i am using janson library to send json body as rest request's , i have notice that i am doing it in this way :
json_t *json_body = json_object();
char sentString[100];
char sentStringSecond[100];
..
json_object_set_new(json_body, "sentString", json_string(sentString));
json_object_set_new(json_body, "sentStringSecond", json_string(sentStringSecond);
..
json_decref(json_body);
is this one call to json_decref is enough to free all of the memory ? my concern are mainly after reading this post json_decref not freeing memory?
You are using a different function to set the JSON strings:
json_object_set_new
instead ofjson_object_set
from the linked question.Your version adds the element to the json-object and "reuses" the reference. It does not increment the counter. Therefore you don't need to decrement it manually. The comment below the answer of that question also mentions
json_object_set_new
.The added element will be free'd together with the main JSON object
json_body
. This meand the reference counters of all sub-objects are decremented automatically. If a counter drops to 0, the object is free'd.If you hold a reference to a sub-object on your own, the object will not be free'd.
Just an example:
You create an object (call
json_string()
) and it will get reference count==1.Variant a) (from the linked question)
You add this object to another object with a new reference. This is done using
json_object_set
. Then the counter is incremented to 2.If you delete the main object (
json_decref(json_body)
) The counter goes down to 1 again but the string is still not released. You need to usejson_decref(srting)
to free the memory.Variant b) (your code)
You add this object to another object with handing over your existing reference. This is done using
json_object_set_new
. Then the counter is preserved at value 1.If you delete the main object (
json_decref(json_body)
) The counter goes down to 0 and now the string is released together with the main object. You do not need to usejson_decref(srting)
to free the memory.