cJSON_Delete
cJSON_Delete释放cJSON构造object时申请的内存资源
通常用法
cJSON *json = cJSON_CreateObject();
...
...
cJSON_Delete(json);
调用cJSON_Delete时产生segmentfault
错误段代码:
cJSON *json = cJSON_CreateObject();
cJSON *payload = cJSON_CreateObject();
...
cJSON_AddItemObject(json, "payloaf", payload);
...
cJSON_Delete(payload);
cJSON_Delete(json);
构造一个json对象 并把payload对象作为一个节点加入到json中
经过debug发现cJSON_Delete(json)时发生了内存越界访问
查看cJSON源码可以发现 cJSON_Delete会主动删除每个节点的资源
CJSON_PUBLIC(void) cJSON_Delete(cJSON *item)
{
cJSON *next = NULL;
while (item != NULL)
{
next = item->next;
if (!(item->type & cJSON_IsReference) && (item->child != NULL))
{
cJSON_Delete(item->child);
}
if (!(item->type & cJSON_IsReference) && (item->valuestring != NULL))
{
global_hooks.deallocate(item->valuestring);
}
if (!(item->type & cJSON_StringIsConst) && (item->string != NULL))
{
global_hooks.deallocate(item->string);
}
global_hooks.deallocate(item);
item = next;
}
}
所以创建使用cJSON构造json对象后 只需要调用cJSON_Delete删除json对象即可
节点的资源会被一并释放掉.