简体   繁体   English

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

[英]Valgrind detects memory leak at fclose()

Why does valgrind say I've got memory leak at the fclose() call? 为什么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 report: 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)

Does it matter to initialize pszOutput or size ? 初始化pszOutputsize是否重要? Or maybe I need to add something else? 还是我需要添加其他内容?

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

The open_memstream() function opens a stream for writing to a buffer. open_memstream()函数打开用于写入缓冲区的流。 The buffer is dynamically allocated (as with malloc(3)), and automatically grows as required. 缓冲区是动态分配的(与malloc(3)一样),并根据需要自动增长。 After closing the stream, the caller should free(3) this buffer. 关闭流后,调用者应释放(3)该缓冲区。

So according to this you need to free(pszOutput) after your file descriptor is closed. 因此,据此,您需要在关闭文件描述符后释放(pszOutput)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM