Reputation: 43578
I have the following code
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <json/json.h>
int main(int argc, char **argv)
{
json_object *new_obj;
char buf[] = "{ \"foo\": \"bar\", \"foo2\": \"bar2\", \"foo3\": \"bar3\" }";
new_obj = json_tokener_parse(buf);
.....
json_object_put(new_obj);
}
Does the json_object_put(new_obj)
free all memory related to new_obj
?
Upvotes: 13
Views: 16747
Reputation: 35
You have to understand how the library works.
json_tokener_parse()
is first, and it creates an object that will act as a memory managing parent that all objects which are created from it use to access the data they define.
So if you get all the way down to making a char *str for a string field, that field doesn't actually store the string, the original object returned from json_tokener_parse()
does.
This is the reason that you can't just use a normal free() and expect things to work as if it was a char array or something.
To be safe, don't use the json_tokener_parse_ex()
function because you will have to also free the object that is the tokener, with json_tokener_parse()
you don't need that argument.
Beyond that, to safely close everything just do:
while (json_object_put(orig_object) != 1) {
// keep freeing
}
You should only need to do that once, but the library may change.
Upvotes: -1
Reputation: 60818
From the documentation:
void json_object_put (struct json_object *this)
Decrement the reference count of json_object and free if it reaches zero
Source: http://oss.metaparadigm.com/json-c/doc/html/json__object_8h.html
Upvotes: 8