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

hop*_*pia 3 c json cjson

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

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

此功能会泄漏内存吗?

Nat*_*tta 5

我从未使用过cJSON,但是根据此链接中提供的函数定义,它看起来像

char *cJSON_Print(cJSON *item)  {return print_value(item,0,1);} 
Run Code Online (Sandbox Code Playgroud)

static char *print_value(cJSON *item,int depth,int fmt);
Run Code Online (Sandbox Code Playgroud)

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

由于我没有追踪IMO分配的方法,因此分配的内存需要free()由调用者函数来分配。否则,将导致内存泄漏。

  • 当时这是正确的,但是正确的API现在是`cJSON_free`。 (2认同)