code
cJSON *body = cJSON_Duplicate(record, true);
cJSON_AddItemToObject(body, KEY_LOG, log);
cJSON *array_pl = cJSON_CreateArray();
cJSON_AddItemToArray(array_pl, body);
cJSON *payload = cJSON_CreateObject();
cJSON_AddItemToObject(payload, KEY_PAYLOAD, array_pl);
cJSON_Delete(body);
cJSON_Delete(array_pl);
cJSON_Delete(payload);
Whenever I use cJSON_Delete() program gets crashed and gives error *** Error in `./sample': free(): invalid pointer: 0xb5db1e18 ***
I searched a lot about this but couldn't found a solution.
Please tell me how this works ?
Quoting from the https://github.com/DaveGamble/cJSON, so please read the documentation.
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.
Reference: Working with the data structure
So you just have to free the body
and it will free the items allocated inside. Removing the other two deletes will solve the problem.
cJSON_Delete(body);