【问题标题】:Memory Leak Using JSON-C使用 JSON-C 的内存泄漏
【发布时间】:2012-02-03 11:49:58
【问题描述】:

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

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

提前致谢

【问题讨论】:

  • 快速网络搜索似乎表明 JSON-C 使用引用计数来管理 json_object 实例,而用于“释放”实例的函数是 json_object_put

标签: c json memory-management memory-leaks json-c


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    是的,我相信您的代码会泄漏内存。问题是您要多次覆盖 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);
    

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

    【讨论】:

    • 不,只要我们没有明确地为 json-object 分配内存,我们只需要为根对象调用一次 json_object_put,这对我有用.....!!
    • 是的,实际上你是对的。您只需为根对象调用一次 put!
    【解决方案3】:

    json_tokener_parse() 将创建一个必须删除的对象。 在这种情况下

    json_object_put(new_obj);

    是必需的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-13
      • 2016-01-27
      • 2010-11-11
      • 2017-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-01
      相关资源
      最近更新 更多