Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/67.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/three.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
调用方是否应该释放cJSON_Print()的返回值?_C_Json_Cjson - Fatal编程技术网

调用方是否应该释放cJSON_Print()的返回值?

调用方是否应该释放cJSON_Print()的返回值?,c,json,cjson,C,Json,Cjson,我正在使用,我有一个函数,如下所示: void printJsonObject(cJSON *item) { char *json_string = cJSON_Print(item); printf("%s\n", json_string); } 此函数是否会泄漏内存?我从未使用过cJSON,但根据本文中的函数定义,它看起来像 char *cJSON_Print(cJSON *item) {return print_value(item,0,1);} 及 从print\

我正在使用,我有一个函数,如下所示:

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

此函数是否会泄漏内存?

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

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

print\u value()
函数中,返回的指针由
cJSON\u strdup()
[这是
malloc()
memcpy()
]组合的修改版本]分配,并返回给调用者


由于我看不到跟踪分配的方法,IMO,调用者函数需要将分配的内存
free()
d。否则,它将是内存泄漏。

是的,它是内存泄漏

调用方必须释放cJSON_Print返回的缓冲区。请使用正确的API(
cJSON\u free
),而不是直接调用stdlib
free

请参阅cJSON维护人员的评论:


我建议:

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

可能的重复在当时是正确的,但是正确的API现在是免费的。
void printJsonObject(cJSON *item)
{
    char *json_string = cJSON_Print(item);
    if (json_string) 
    {
        printf("%s\n", json_string);
        cJSON_free(json_string);
    }
}