内存泄漏使用JSON-C

Mad*_*oor 8 c json memory-leaks memory-management json-c

我是JSON-C的新手,请查看我的示例代码,让我知道它会创建任何内存泄漏,如果是,那么如何释放JSON-C对象.

    struct json_object *new_obj         = NULL;
    new_obj = json_tokener_parse(strRawJSON);
    new_obj = json_object_object_get(new_obj, "FUU");
    if(NULL == new_obj){
        SYS_OUT("\nFUU not found in JSON");
        return NO;
    }
    new_obj = json_object_object_get(new_obj, "FOO"); // I m re-using new_obj, without free it?  
    if(NULL == new_obj){
        SYS_OUT("\nFOO not found in JSON");
        return NO;
    }
    // DO I need to clean new_obj, if yes then how ??
Run Code Online (Sandbox Code Playgroud)

我是否需要清理new_obj,如果是,那么如何.有人可以帮助理解如何进行内存管理JSON-C.

提前致谢

Mad*_*oor 8

不,我们只需要为根对象调用json_object_put一次,只要我们没有明确地将内存分配给json-object,这对我有用..... !!


por*_*ast 6

是的,我相信你的代码会泄漏内存.问题是你多次覆盖你的new_obj指针.你的代码应该是这样的:

struct json_object *new_obj, *fuu_obj, *foo_obj;
new_obj = json_tokener_parse(strRawJSON);
fuu_obj = json_object_object_get(new_obj, "FUU");
if(NULL == new_obj){
    SYS_OUT("\nFUU not found in JSON");
    return NO;
}
foo_obj = json_object_object_get(new_obj, "FOO"); 
if(NULL == new_obj){
    SYS_OUT("\nFOO not found in JSON");
    return NO;
}
json_object_put(foo_obj);
json_object_put(fuu_obj);
json_object_put(new_obj);
Run Code Online (Sandbox Code Playgroud)

如果这对你有用,请告诉我.如果您需要更多帮助,json-c有一个引用计数模式,可以为您提供有关对象的更多信息.让我知道,我可以详细说明这一点.

  • 不,我们只需要为根对象调用json_object_put一次,只要我们没有明确地将内存分配给json-object,这对我有用..... !! (4认同)
  • 是的,实际上你是对的。您只需要为根对象调用一次 put ! (2认同)