I am using libjosn-c as below and encounter a Segmentation fault error.
If I remove the line json_object_object_add(root, "Child", value);, no error occurs.
int main(int argc, char **argv)
{
json_object *root = NULL, *value = NULL;
root = json_object_new_string("My Object");
value = json_object_new_string("My Child Object");
json_object_object_add(root, "Child", value);
printf("to string =%s\n", json_object_to_json_string(root));
json_object_put(value);
json_object_put(root);
return 0;
}
I am not experienced in libjson-c.
Thanks for your help!
If I were you, I'd read the documentation of a library before starting to use it.
As described here
json_object_object_add(root, "Child", value)transfers the ownership ofvaluetoroot. It means you are no longer responsible forjson_object_puting it. When youjson_object_puttherootitjson_object_puts thevaluefor you.When you
json_object_putthevalue, it's reference counter drops to 0 and it's memory gets freed. When youjson_object_puttheroot, it attempts tojson_object_putthevalueand fails because thevalueno longer exists.If you don't want the
valueto outlive theroot, just remove thejson_object_put(value)line.If you want to use
valueafterrootgets freed, use:json_object_object_add(root, "Child", json_object_get(value))