流泄漏内存

ofstream leaking memory

本文关键字:内存 泄漏      更新时间:2023-10-16

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

问题是它似乎泄露了内存。它所运行的系统是CentOS 64位,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;
};

流在其他地方被初始化和销毁,但本质上它们仍然"永远"开放供写入。

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在缓存方面非常激进,因此它将使用几乎所有的可用内存,但每当应用程序需要更多内存时,它就会释放一些内存并将其授予应用程序。

使用vmstat(手册页)

vmstat -S m 1

它将显示缓存和缓冲内存。请注意,缓冲区内存是易失性的,一旦应用程序请求,它就会自动释放

我可以通过登录在我的8GB桌面(linux)上轻松地显示效果,只需执行"dd if=/dev/sda of=/dev/null";缓冲存储器将稳定地消耗所有的可用存储器。

这是的设计

一些相关链接:

  • http://sourcefrog.net/weblog/software/linux-kernel/free-mem.html
  • http://tldp.org/LDP/tlk/fs/filesystem.html
  • 谷歌搜索:linux无内存可用缓存缓冲区