cJSON memory leak

拥有回忆 提交于 2019-12-19 10:52:30

问题


I use cJSON in my program to convert my values to JSON and write it to file. Here is the example of my code:

void writeStructToFile(IOPipe this, struct structtype somevalues) {
    cJSON *jout = cJSON_CreateObject();
    cJSON_AddItemToObject(jout, "V1", cJSON_CreateNumber(somevalues.v1));
    cJSON_AddItemToObject(jout, "V2", cJSON_CreateNumber(somevalues.v2));
    fprintf(this->outstream, "%s", cJSON_Print(jout));
    cJSON_Delete(jout);
}

Works great, but after some time I found that Linux(embedded) kills my program because of abnormal memory use or device(on Cortex A8) just hangs. After debug I found, that leak appears exactly in this function even though I delete the pointer at the end. Could anyone see that leak?


回答1:


Initially I thought that it might be FILE I/O's internal buffers. But these are flushed automatically when they become too big.

The real leak is that cJSON_Print allocates memory: a char array. You must free this after you're done:

char* text = cJSON_Print(jout);
fprintf(this->outstream, "%s", text);
free(text);  // As suggested by PaulPonomarev.

cJSON_Delete(jout);



回答2:


For a char* allocated cJSON_Print, it is said to use cJSON_FreePrintBuffer.



来源:https://stackoverflow.com/questions/26158734/cjson-memory-leak

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!