为什么 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)
初始化 pszOutput
或 size
重要吗?还是我需要添加其他内容?
最佳答案
发件人: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/