【问题标题】:resource leak : fExclfile资源泄漏:fExclfile
【发布时间】:2016-04-13 04:59:59
【问题描述】:

在 Cppcheck 中检查我的代码时,我收到错误“资源泄漏:fExclfile”。我的程序没有给出任何编译错误或崩溃。请帮我解决这个问题。

FILE           *fExclfile = NULL;
FILE           *fExclBadfile = NULL;
if (ExclBadfile != NULL) {
    fExclBadfile = fopen(ExclBadfile, "a");
    if (fExclBadfile == NULL) {
        fprintf(stderr, "%s Can't open the exclusion bad file \"%s\". Check permissions.\n", t_stamp(), ExclBadfile);
        fflush(stderr);
        return 0;   // <- getting resource leak -> 
    };
};

【问题讨论】:

  • 你确定这不是 fExclBadfile 的资源泄漏,当你返回时你没有关闭它?您没有使用 fExclfile,因此资源泄漏没有任何意义。
  • ExclBadfile 是什么,为什么要在堆上分配它?如果它是堆上的资源并且在退出时没有销毁它,那么这就是潜在的内存泄漏
  • 对不起@Matt Jordan。它是“资源泄漏:fExclBadfile”。
  • @Matt Jordan:如果我添加 'fclose(ExlBadfile);在return 0之前,能解决问题吗?
  • 是的,我认为 fclose(fExclBadfile) 会解决问题,因为它会清理 fopen 分配的资源。

标签: c++ memory-leaks static-code-analysis cppcheck resource-leak


【解决方案1】:

只需确保在程序退出之前关闭所有打开的文件句柄,如果 ExclBdfile 是在堆上创建的,也需要释放它

【讨论】:

    猜你喜欢
    • 2014-02-10
    • 1970-01-01
    • 2020-12-09
    • 2012-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-15
    • 2010-10-29
    相关资源
    最近更新 更多