调用者是否应该释放cJSON_Print()的返回值? [英] Should the return value of cJSON_Print() be freed by the caller?

查看:1166
本文介绍了调用者是否应该释放cJSON_Print()的返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 cJSON库,并且具有如下功能:

I am using the cJSON library and I have a function as follows:

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

此功能会泄漏内存吗?

推荐答案

我从未使用过cJSON,但是根据

I've never used cJSON , but as per the function definition present in this link, it looks like

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()的组合的修改版本]分配,并返回给调用方.

From print_value() function, the pointer returned is allocated by cJSON_strdup() [which is a modified version of the combination of malloc() and memcpy()] and it is returned to the caller.

正如我所见,没有任何方法可以跟踪IMO的分配,因此调用方函数需要free() d分配已分配的内存.否则,将导致内存泄漏.

As I see no method to track the allocation, IMO, the allocated memory needs to be free()d by the caller function. Otherwise, it will be a memory leak.

这篇关于调用者是否应该释放cJSON_Print()的返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆