Valgrind在fclose()检测到内存泄漏

时间:2016-03-15 15:54:34

标签: c++ valgrind fclose

为什么valgrind说fclose()来电时我的内存泄漏?

#include <stdio.h>

class Stream
{
    public:
        Stream();
        ~Stream();
    private:
        char*  pszOutput;
        size_t size;
        FILE* file;
};

Stream::Stream()
{
    file = open_memstream(&pszOutput, &size);
}

Stream::~Stream()
{
    fclose(file);
}

int main()
{
    Stream s;   

    return 0;
}

Valgrind报告:

==52387== 1 bytes in 1 blocks are definitely lost in loss record 1 of 1
==52387==    at 0x4C28CCE: realloc (vg_replace_malloc.c:632)
==52387==    by 0x5639CA3: _IO_mem_finish (memstream.c:132)
==52387==    by 0x5635956: fclose@@GLIBC_2.2.5 (iofclose.c:66)

初始化pszOutputsize是否重要?或者我可能需要添加别的东西?

1 个答案:

答案 0 :(得分:3)

来自:http://linux.die.net/man/3/open_memstream

  

open_memstream()函数打开一个用于写入缓冲区的流。缓冲区是动态分配的(与malloc(3)一样),并根据需要自动增长。关闭流后,调用者应释放(3)此缓冲区。

因此,根据这一点,您需要在文件描述符关闭后 free(pszOutput)