c++ - ofstream 泄漏内存

标签 c++ memory-leaks ofstream

我有一个 C++ 类,它将其数据写出到二进制 std::ofstream。该类将数据存储为 boost:shared_array 但我已经消除了这个问题。问题出在 ofstream 上对 write() 的调用。

问题是它似乎会泄漏内存。其运行系统为CentOS 64bit,GCC 4.1.2。

在应用程序运行时查看 topfree 时,可执行文件本身不会继续消耗内存(由 Netbeans 中的内存分析器备份),但是可用系统内存量确实会随着时间的推移而减少。更重要的是,当应用程序退出时,此内存不会被回收!

这是一个特殊问题,因为目的是连续数小时以大约 50MB/s 的速度连续写入磁盘。然而,一旦我们将可用系统内存降低到大约 90MB,它似乎就“稳定”了,不再进一步减少,应用程序继续正常运行。然而,它确实会为其他正在运行的进程搞砸系统,这很糟糕,mmkay。

下面是导致悲痛的类的稍微简化的版本。

class WritableMessage
{
public:
    WritableMessage();
    void write(std::ofstream* const idxStream, std::ofstream* const dataStream);

private:
    IdxRecord m_idx;
    boost::shared_array<char> m_data;
};

ofstreams 在别处初始化和销毁​​,但本质上它们“永远”保持打开状态以供写入。

void WritableMessage::write(std::ofstream* const idxStream, std::ofstream* const dataStream)
{
    //Call the IdxRecord to write itself (just a call to idxStream->write())
    m_idx.write(idxStream, dataStream->tellp());

    //This is the main issue, because this data can be up to about 2MB in size
    //for each write.  Commenting out this line removes all issues with the memory leak
    dataStream->write(m_data.get(), m_idx.getMessageSize());

    //I'd expect the flush to clear any buffers that the ofstream maintains,
    //but apparently not
    idxStream->flush();
    dataStream->flush();
}

最佳答案

看起来您没有问题,这只是系统缓存按预期工作。 Linux 在缓存方面非常积极,因此它会为此使用几乎所有可用内存,但每当应用程序需要更多内存时,它会释放部分内存并将其授予应用程序。

关于c++ - ofstream 泄漏内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6424050/

相关文章:

c++ - 构建管理 : Eclipse project vs Eclipse Managed Make project

memory - Node.js v8-profiler 模块不会安装

c++ - 我的 Lua 对象被收集了吗?

c++ - 在 C++ 文件中写入 n 字节的最快方法

c++ - 是否存在使用 Purify 导致 SIGABRT 在 g++ 中抛出异常的已知问题?

c++ - 分配运算符(operator)在圆形双向链表中无法正常工作

c++ - 是在连续空间中分配的嵌套 vector

java - PermGen 会泄漏到 native 堆中吗?

c++ - 写入文件的 C++ 中双重类型的意外舍入

c++ - ofstream 在看门狗超时前将文件刷新到磁盘