1

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?

Omer Anisfeld
  • 1,236
  • 12
  • 28

1 Answers1

4

You are using a different function to set the JSON strings: json_object_set_new instead of json_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 use json_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 use json_decref(srting) to free the memory.

Gerhardh
  • 11,688
  • 4
  • 17
  • 39
  • and the json_string(sentString) is also doing malloc , is it get free in this json_decref(json_body); line? or that i need a separate free for that as well? – Omer Anisfeld May 08 '18 at 07:54
  • Yes, all sub-objects are free'd as well as soon as the reference count drops to 0. – Gerhardh May 08 '18 at 08:00
  • so i need to do several time json_decref? how many time ? according to the number of times i made json_object_set_new with a new json_string? – Omer Anisfeld May 08 '18 at 08:10
  • tank's, so for my understanding in the code i post there is no memory leak no for the json_t *json_body = json_object(); and not for the return reference that i am not saving for json_string() function ? right? – Omer Anisfeld May 08 '18 at 12:53