c++ - Valgrind 在 fclose() 处检测到内存泄漏

标签 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 重要吗?还是我需要添加其他内容?

最佳答案

发件人:http://linux.die.net/man/3/open_memstream

The open_memstream() function opens a stream for writing to a buffer. The buffer is dynamically allocated (as with malloc(3)), and automatically grows as required. After closing the stream, the caller should free(3) this buffer.

因此,根据这个,您需要在文件描述符关闭后释放(pszOutput)

关于c++ - Valgrind 在 fclose() 处检测到内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36016168/

相关文章:

c++ - 如何重建旧库以在最新的 Visual Studio 上工作?

c - Valgrind 关于 asprintf : address is 0 bytes inside a block of size <size> alloc'd

c++ - 程序在 fclose() 上崩溃

c- valgrind(无效的 free()/delete/delete[]/realloc())套接字

c - 程序因 fclose 而崩溃

c - fclose() 导致段错误

c++ - 初学者 C++ - 字符串比较

c++ - 我不明白为什么 map 会导致段错误

c++ - 为什么省略 "#include <string>"只是有时会导致编译失败?

c - 使用结构作为键修改示例时出现 UTHash 段错误