【问题标题】:leak detected using valgrind when using fopen使用 fopen 时使用 valgrind 检测到泄漏
【发布时间】:2010-08-29 10:35:33
【问题描述】:

gcc 4.4.4 c89 valgrind 3.5.0.

当我使用文件指针打开文件时检测到泄漏。

==17681==    in use at exit: 352 bytes in 1 blocks
==17681==    total heap usage: 1 allocs, 0 frees, 352 bytes allocated
==17681== 
==17681==    352 bytes in 1 blocks are still reachable in loss record 1 of 1
==17681==    at 0x4005BDC: malloc (vg_replace_malloc.c:195)
==17681==    by 0xAAD67E: __fopen_internal (iofopen.c:76)
==17681==    by 0xAAD74B: fopen@@GLIBC_2.1 (iofopen.c:107)

它指向的代码行是这个fopen:

FILE *fp = NULL;
fp = fopen("input.txt", "r");
if(fp == NULL) {
    fprintf(stderr, "Failed to open file [ %s ]\n", strerror(errno));
    exit(1);
}

可能是 fopen 函数正在分配内存而不是释放它吗?如何释放此内存?

非常感谢您的任何建议,

【问题讨论】:

    标签: c valgrind


    【解决方案1】:

    你没有关闭你的文件*。

    【讨论】:

    • 不要FILE * 上致电free。你打电话给fclose
    • 尽管使用了fclose,但我看到了完全相同的错误。
    【解决方案2】:

    我遇到了同样的问题

    我用 fflush() 解决了它

    // Stream needs to be flushed before closing
    fflush ( fp);
    
    fclose( fp);
    

    【讨论】:

      【解决方案3】:

      如果你在文件上调用fclose,我猜它会释放它。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-02-28
        • 2011-04-19
        • 1970-01-01
        • 2022-01-05
        • 1970-01-01
        相关资源
        最近更新 更多