I am using the json-c in my C program (not C++). I am getting segfaults from time to time and trying to debug. To be honest, I might not have the full understanding how the library works so I am looking for any advice.
This is partially how I am using:
char* createjsonstatusstring()
{
json_object *jsonmain,
*jsontmp;
const char *conststring;
char *string;
jsonmain = json_object_new_object();
jsontmp = json_object_new_object();
json_object_object_add(jsontmp,"test",json_object_new_string("Beispiel"));
json_object_object_add(jsontmp,"test2",json_object_new_string("Beispiel2"));
json_object_object_add(jsonmain,"Data",jsontmp);
conststring = json_object_to_json_string_ext(jsonmain,JSON_C_TO_STRING_SPACED | JSON_C_TO_STRING_PRETTY);
json_object_put(jsontmp);
json_object_put(jsonmain);
string = malloc(strlen(conststring)+1);
strcpy(string,conststring);
return string;
}
When doing the last json_object_put
I am getting the segfault.
Can you explain why and how to improve?
Thanks!
/KNEBB
From https://json-c.github.io/json-c/json-c-0.10/doc/html/json__object_8h.html#a04448b1c63173e1bfe49965835732075 :
and
You do not have ownership in
jsontmp
, so doingjson_object_put(jsontmp);
is invalid. Just only calljson_object_put(jsonmain);
,jsonmain
has ownership ofjsontmp
.