4

I have the following code and I want to clean a json object created by json_object_new_string().

#include <json/json.h>
#include <stdio.h>

int main() {
  /*Creating a json object*/
  json_object * jobj = json_object_new_object();

  /*Creating a json string*/
  json_object *jstring = json_object_new_string("Joys of Programming");


  /*Form the json object*/
  json_object_object_add(jobj,"Site Name", jstring);

  /*Now printing the json object*/
  printf ("The json object created: %sn",json_object_to_json_string(jobj));

  /* clean the json object */
  json_object_put(jobj);

}

Does the line json_object_put(jobj); clean both jobj and jstring ?

Or I have to a clean jstring alone with json_object_put(jstring);?

Edit

question2

what will be the behaviour if the jstring is creted into a function in this way?

#include <json/json.h>
#include <stdio.h>

static void my_json_add_obj(json_object *jobj, char *name, char *val) {
      /*Creating a json string*/
      json_object *jstring = json_object_new_string(val);


      /*Form the json object*/
      json_object_object_add(jobj,name, jstring);
}

int main() {
  /*Creating a json object*/
  json_object * jobj = json_object_new_object();

  my_json_add_obj(jobj, "Site Name", "Joys of Programming")

  /*Now printing the json object*/
  printf ("The json object created: %sn",json_object_to_json_string(jobj));

  /* clean the json object */
  json_object_put(jobj);

}

the jstring in this case is a local variable into a function. Does the json_object_put(jobj); will clean the jstring (created in the function my_json_add_obj()) ?

MOHAMED
  • 41,599
  • 58
  • 163
  • 268

1 Answers1

7

json_object_put will free everything referenced by the object. So yes, it's sufficient to use that function on jobj to free the whole object.

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
  • what will be the behaviour if the `jstring` is creted into a function? please refer to the question I edited it – MOHAMED Aug 22 '13 at 14:23
  • 2
    Please stop doing this. It is not acceptable Stack Overflow behavior to completely change a question after someone has posted an answer. Anyway, it doesn't matter where you do it. As long as the string is part of the object it will be free'd with it. – ThiefMaster Aug 22 '13 at 14:27