1

我有一个 C++ 类,它将其数据写入二进制文件std::ofstream。该类将数据存储为 aboost:shared_array但我已将其作为问题消除。问题在于write()ofstream.

问题是它似乎泄漏了内存。它运行的系统是 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();
}
4

2 回答 2

4

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

于 2011-06-21T11:22:03.740 回答
3

使用 vmstat(手册页

vmstat -S m 1

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

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

这是设计使然

一些相关链接:

于 2011-06-21T11:30:44.327 回答