如何清理"json_object_new_string"创建的json对象?

MOH*_*MED 4 c json json-c

我有以下代码,我想清理由创建的json对象json_object_new_string().

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

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

  /*Creating a json string*/
  json_object *jstring = json_object_new_string("Joys of Programming");


  /*Form the json object*/
  json_object_object_add(jobj,"Site Name", jstring);

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

  /* clean the json object */
  json_object_put(jobj);

}
Run Code Online (Sandbox Code Playgroud)

是否行json_object_put(jobj);清洗都jobjjstring

或者我必须jstring单独干净json_object_put(jstring);

编辑

问题2

如果jstring以这种方式创建一个函数会有什么行为?

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

static void my_json_add_obj(json_object *jobj, char *name, char *val) {
      /*Creating a json string*/
      json_object *jstring = json_object_new_string(val);


      /*Form the json object*/
      json_object_object_add(jobj,name, jstring);
}

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

  my_json_add_obj(jobj, "Site Name", "Joys of Programming")

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

  /* clean the json object */
  json_object_put(jobj);

}
Run Code Online (Sandbox Code Playgroud)

jstring这种情况下是一个局部变量成一个函数.是否json_object_put(jobj);会清理jstring(在函数中创建my_json_add_obj())?

Thi*_*ter 6

json_object_put将释放对象引用的所有内容.所以是的,使用该函数jobj释放整个对象就足够了.

  • 请停止这样做。在某人发布答案后完全更改问题的 Stack Overflow 行为是不可接受的。无论如何,在哪里做并不重要。只要字符串是对象的一部分,它就会随之释放。 (2认同)