C语言中的文件内存泄漏

C语言中的文件内存泄漏,c,memory,valgrind,C,Memory,Valgrind,我有一个简单的代码,用于在c中写入文件 FILE* fp = fopen ("file.txt", "w+"); fprintf(fp, "bla"); free(fp); 我在运行valgrind时犯了很多错误 Address "xxxxxxx" is 192 bytes inside a block of size 568 free'd Address "xxxxxxx" is 168 bytes inside a block of size 568 free'd 还有很多类似的。

我有一个简单的代码,用于在c中写入文件

FILE*  fp = fopen ("file.txt", "w+");
fprintf(fp, "bla");
free(fp);
我在运行valgrind时犯了很多错误

 Address "xxxxxxx" is 192 bytes inside a block of size 568 free'd
 Address "xxxxxxx" is 168 bytes inside a block of size 568 free'd
还有很多类似的。 没有泄漏!,但是错误。

您应该用fclose(fp)替换free(fp)。
还要检查fp是否为空

关闭用打开的文件需要调用。调用*是未定义的行为


valgrind错误告诉您,您试图
释放的
地址在分配的内存块中。通常,您只能
释放
分配给
malloc
的整个内存块,因此您必须提供块开头的地址。

fopen
必须与
fclose
配对:

FILE* fp = fopen("file.txt", "w+");
if (fp) {
  // ...
  if (0 != fclose(fp)) {
    // error when closing the file; data may be lost
  }
} else {
  // could not open file
}