打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Memory Leak Using JSON
userphoto

2014.08.15

关注

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

asked Jan 5 '12 at 16:39
    
A quick web search seems to indicate that JSON-C uses reference counting to manage json_object instances and the function used to "free" the instances is json_object_put. –  hmjd Jan 5 '12 at 16:50

2 Answers

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.

answered Mar 6 '12 at 3:41
portforwardpodcast
1,9841227
2  
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.....!! –  Madhu S. Kapoor Mar 12 '12 at 16:11
    
Yes actually you are right. You only need to call put one time for the root object! –  portforwardpodcast Apr 5 '12 at 18:05
up vote 3 down vote accepted

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.....!!

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
在PHP语言中使用JSON
Windows,LINUX下QT使用json
JSON c语言开发指南
Leak Free Javascript Closures
memcached: a distributed memory object cachin...
json示例
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服