我正在使用cJSON库,并且具有以下功能:
void printJsonObject(cJSON *item)
{
char *json_string = cJSON_Print(item);
printf("%s\n", json_string);
}
Run Code Online (Sandbox Code Playgroud)
此功能会泄漏内存吗?
我从未使用过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()由调用者函数来分配。否则,将导致内存泄漏。