如何使用FILE *打开文件后释放泄漏内存?



所以,我正在遭受内存泄漏!程序如下:

#include <string.h>
#include <assert.h>
#include <ctype.h>
#include <stdlib.h>
int main(int b, char** locations) {
struct pair* table[size];
createTable(table);
int look = 0;
FILE * textFile;
look = 1;
int doing = 0;

while (locations[look] != NULL) {
textFile = fopen(locations[2], "r");
//textFile = fopen(locations[look], "r");
look++;
doing++;
//free(textFile);
}

}

根据valgrind有2个泄漏,我如何解决这个问题?程序以./main -12 folder/example.txt folder/example2.txt...

的形式接受输入试图释放每个FILE *不工作,它会导致程序无限运行。还要记住,这只是一个代码片段,这是我的MRE,我将泄漏范围缩小到。

textfile不能是free()d,但可以是fclose(),并且所有分配给运行它的内部内存将被stdio库释放。

不能释放泄漏的内存,因为泄漏的含义来自于无法获得分配它的地址的引用。你已经用那个内存的地址覆盖了你的指针,现在你没有任何方法在你的虚拟地址空间中定位那个内存。

最新更新