free all the memory allocated to json objects

363 views
Skip to first unread message

kumar rahul

unread,
Jan 20, 2020, 1:19:14 PM1/20/20
to json-c
Hi All

   I have question related to freeing the memory assigned to json objects

Here is a sample code

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

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

  /*Creating a json array*/
  json_object *jarray = json_object_new_array();

  /*Creating json strings*/
  json_object *jstring1 = json_object_new_string("c");
  json_object *jstring2 = json_object_new_string("c++");
  json_object *jstring3 = json_object_new_string("php");

  /*Adding the above created json strings to the array*/
  json_object_array_add(jarray,jstring1);
  json_object_array_add(jarray,jstring2);
  json_object_array_add(jarray,jstring3);

  /*Form the json object*/
  json_object_object_add(jobj,"Categories", jarray);

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

}


In the above code we are creating json objects. Do we need to free memory explicitly before exiting the code? If yes then does free will work? It will be great if
For the above code somebody can state free statements.

Thanks
Rahul

Eric Hawicz-Song

unread,
Jan 20, 2020, 9:05:10 PM1/20/20
to jso...@googlegroups.com
On Mon, Jan 20, 2020, 1:19 PM kumar rahul <rahul2...@gmail.com> wrote:
Here is a sample code
... 
  json_object * jobj = json_object_new_object();
... 
In the above code we are creating json objects. Do we need to free memory explicitly before exiting the code? If yes then does free will work? It will be great if 
For the above code somebody can state free statements.
If your program is exiting then whether you free the memory or not is moot: the process and all of its memory, however obtained, will be cleaned up by the OS anyway.  
However, it's often good practice to free the objects you create anyway, in case you decide to re-use that code in a longer running program.
You can do that by calling json_object_put() on the root object of each independent object tree that you have. Your example code has just a single tree, so calling json_object_put(jobj) would be sufficient.

Eric

kumar rahul

unread,
Jan 20, 2020, 10:01:50 PM1/20/20
to json-c

Hi Eric

    Thank you for quick response. Much appreciated.

Thanks
Rahul
Reply all
Reply to author
Forward
0 new messages