cJSON内存泄漏 [英] cJSON memory leak
问题描述
我用cJSON在我的计划,以我的价值观转换成JSON并将其写入到文件。这里是我的code的例子:
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);
}
伟大的作品,但一段时间后我发现,Linux操作系统(嵌入式)杀死,因为异常内存使用或设备(在Cortex A8的),我的程序只是挂起。调试后,我发现,这正是泄漏出现在此功能,即使我在最后删除指针。任何人都可以看到泄漏?
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?
推荐答案
起初我以为这可能是文件
I / O的内部缓冲区。但是,当他们变得过于庞大,这些都是会自动刷新。
Initially I thought that it might be FILE
I/O's internal buffers. But these are flushed automatically when they become too big.
真正的泄漏是 cJSON_Print
分配内存:一个字符
阵列。大功告成后,您必须释放这样的:
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);
这篇关于cJSON内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!