【问题标题】:Should the return value of cJSON_Print() be freed by the caller?调用者是否应该释放 cJSON_Print() 的返回值?
【发布时间】:2014-12-10 06:13:22
【问题描述】:

我正在使用cJSON library,我的功能如下:

void printJsonObject(cJSON *item)
{
    char *json_string = cJSON_Print(item);
    printf("%s\n", json_string);
}

这个函数会泄漏内存吗?

【问题讨论】:

标签: c json cjson


【解决方案1】:

我从未使用过 cJSON ,但根据此 link 中的函数定义,它看起来像

char *cJSON_Print(cJSON *item)  {return print_value(item,0,1);} 

和

static char *print_value(cJSON *item,int depth,int fmt);

从print_value()函数,返回的指针由cJSON_strdup()分配[这是malloc()和memcpy()组合的修改版本],并返回给调用者。

由于我没有看到任何跟踪分配的方法,IMO,分配的内存需要由调用者函数为free()d。否则就是内存泄漏。

【讨论】:

  • 这在当时是正确的,但现在正确的 API 是 cJSON_free。
【解决方案2】:

是的,这是内存泄漏。

cJSON_Print 返回的缓冲区必须由调用者释放。请使用正确的 API (cJSON_free) 而不是直接调用 stdlib free。

查看 cJSON 维护者的评论:https://github.com/DaveGamble/cJSON/issues/5#issuecomment-298469697


我推荐:

void printJsonObject(cJSON *item)
{
    char *json_string = cJSON_Print(item);
    if (json_string) 
    {
        printf("%s\n", json_string);
        cJSON_free(json_string);
    }
}

【讨论】:

    猜你喜欢
    • 2010-11-20
    • 1970-01-01
    • 1970-01-01
    • 2015-05-20
    • 1970-01-01
    • 1970-01-01
    • 2011-03-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多