Should the return value of cJSON_Print() be freed by the caller?

☆樱花仙子☆ 提交于 2019-12-23 22:44:03

问题


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);
}

Will this function leak memory?


回答1:


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);} 

and

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

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.

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.



来源:https://stackoverflow.com/questions/27394364/should-the-return-value-of-cjson-print-be-freed-by-the-caller

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!