【发布时间】:2014-12-10 06:13:22
【问题描述】:
我正在使用cJSON library,我的功能如下:
void printJsonObject(cJSON *item)
{
char *json_string = cJSON_Print(item);
printf("%s\n", json_string);
}
这个函数会泄漏内存吗?
【问题讨论】:
-
cJSON memory leak的可能重复
我正在使用cJSON library,我的功能如下:
void printJsonObject(cJSON *item)
{
char *json_string = cJSON_Print(item);
printf("%s\n", json_string);
}
这个函数会泄漏内存吗?
【问题讨论】:
我从未使用过 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。否则就是内存泄漏。
【讨论】:
cJSON_free。
是的,这是内存泄漏。
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);
}
}
【讨论】: