【问题标题】:File memory leak in CC中的文件内存泄漏
【发布时间】:2015-08-15 18:25:52
【问题描述】:

我有这个在 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 memory valgrind


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      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
      }
      

      【讨论】:

        【解决方案3】:

        关闭使用fopen 打开的文件需要调用fclose。在FILE* 上调用free未定义的行为

        valgrind 错误告诉您,您尝试free 的地址是一块分配的内存中。一般来说,您只能free 分配给malloc 的整个内存块,因此您必须提供块开始的地址。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2010-12-20
          • 2010-10-11
          • 1970-01-01
          • 2016-01-27
          • 2010-11-11
          • 2017-02-18
          • 1970-01-01
          • 2010-09-18
          相关资源
          最近更新 更多