在C库中使用json_object_put()



我在我的C程序(不是c++)中使用json-c。我不时地得到段错误,并试图调试。老实说,我可能没有完全理解图书馆是如何工作的,所以我正在寻求任何建议。

这是我使用的部分方式:

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;
}

当做最后一个json_object_put时,我得到了段故障。你能解释一下为什么以及如何改进吗?

谢谢!

/KNEBB

From https://json-c.github.io/json-c/json-c-0.10/doc/html/json__object_8h.html#a04448b1c63173e1bfe49965835732075:

void json_object_object_add     (   struct json_object *    obj,
const char *    key,
struct json_object *    val  
)   
Upon calling this, the ownership of val transfers to obj. [..]

void json_object_put    (   struct json_object *    obj      )      
Decrement the reference count of json_object and free if it reaches zero. You must have ownership of obj prior to doing this or you will cause an imbalance in the reference count.

您在jsontmp中没有所有权,因此执行json_object_put(jsontmp);无效。只调用json_object_put(jsonmain);,jsonmain拥有jsontmp的所有权。

相关内容

最新更新