C中的文件内存泄漏

File memory leak in C

我有这个简单的代码可以写入 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

还有很多类似的。 没有泄漏!但有错误。

您应该将 free(fp) 替换为 fclose(fp)。 同时检查 fp 是否为 NULL

关闭使用 fopen requires a call to fclose. Calling free on a FILE* 打开的文件是 未定义的行为

valgrind 错误告诉您,您尝试 free 的地址 分配的内存块中。通常,您只能 free 分配给 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
}