Memory Leak Using JSON-C

荒凉一梦 提交于 2019-12-21 09:31:50

问题


I am new to JSON-C, Please see my sample code and let me know of it will create any memory leak, if yes then how to free JSON-C object.

    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 ??

Do I need to clean new_obj, if yes then how. Can some one help to understand how to do memory management JSON-C.

Thanks in Advance


回答1:


NO, We need to call json_object_put only once for root object as long as we are not explicitly allocating memory to json-object and this worked for me.....!!




回答2:


Yes, I believe your code will leak memory. The problem is that you are overwriting your new_obj pointer multiple times. Your code should be something like this:

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

Please let me know if this works for you. If you want more help, json-c has a reference count mode which can give you more information about objects. Let me know and I can elaborate on this more.




回答3:


json_tokener_parse() will create an object which must be deleted. in this case

json_object_put(new_obj);

is required.



来源:https://stackoverflow.com/questions/8746155/memory-leak-using-json-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!