主要涉及两个释放内存的函数:cJSON_free和cJSON_Delete,该项目在github上有如下说明:

Printing JSON

Given a tree of cJSON items, you can print them as a string using cJSON_Print.

char *string = cJSON_Print(json);

It will allocate a string and print a JSON representation of the tree into it. Once it returns, you are fully responsible for deallocating it after use with your allocator. (usually free, depends on what has been set with cJSON_InitHooks).

也就是说调用cJSON_Print(以及cJSON_PrintUnformatted)后,必须自行释放内存,对于1.5版本及以上的cJSON可以使用cJSON_free函数,其他版本直接使用free也可,示例代码如下:

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

另一段说明如下:

For every value type there is a cJSON_Create... function that can be used to create an item of that type. All of these will allocate a cJSON struct that can later be deleted with cJSON_Delete. Note that you have to delete them at some point, otherwise you will get a memory leak.
Important: If you have added an item to an array or an object already, you mustn't delete it with cJSON_Delete. Adding it to an array or object transfers its ownership so that when that array or object is deleted, it gets deleted as well. You also could use cJSON_SetValuestring to change a cJSON_String's valuestring, and you needn't to free the previous valuestring manually. 

对于cJSON_Create..形式的函数,需要使用cJSON_Delete函数释放内存,示例代码如下:

cJSON *json=cJSON_CreateObject();
cJSON_Delete(json);

需要注意两个函数不能混用,否则内存无法正确释放,目前来看除了打印的函数使用cJSON_free,其他cJSON_Create..形式的函数都使用cJSON_Delete。

此外注意上面的“Important:”部分的说明,意思是如果你把一个item添加到一个数组或者object里,不能直接释放item,因为它已经包含在被添加到数组或者object里了,删除数组或object时被添加的item同时也会被删除。个人试验时发现如果释放item后再删除object程序将崩溃。

最后一点,如果使用cJSON_Replace..形式的函数,原来的item会被删除,所以不必担心原item内存泄露的问题,github说明如下

You can also replace an item in an array in place. Either with cJSON_ReplaceItemInArray using an index or with cJSON_ReplaceItemViaPointer given a pointer to an element. cJSON_ReplaceItemViaPointer will return 0 if it fails. What this does internally is to detach the old item, delete it and insert the new item in its place.

You can also replace an item in an object in place. Either with cJSON_ReplaceItemInObjectCaseSensitive using a key or with cJSON_ReplaceItemViaPointer given a pointer to an element. cJSON_ReplaceItemViaPointer will return 0 if it fails. What this does internally is to detach the old item, delete it and insert the new item in its place.

 

参考:

1. https://github.com/DaveGamble/cJSON#working-with-the-data-structure

2.https://github.com/DaveGamble/cJSON#printing-json

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

 

 

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐