我有一个 C++ 类,它将其数据写入二进制文件std::ofstream
。该类将数据存储为 aboost:shared_array
但我已将其作为问题消除。问题在于write()
对ofstream
.
问题是它似乎泄漏了内存。它运行的系统是 CentOS 64bit,GCC 4.1.2。
当应用程序运行时top
,free
可执行文件本身不会继续消耗内存(由 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();
}