流泄漏内存
ofstream leaking memory
我有一个C++类,它将数据写入二进制std::ofstream
。该类将数据存储为boost:shared_array
,但我已经消除了这一问题。问题出在对ofstream
上的write()
的调用上。
问题是它似乎泄露了内存。它所运行的系统是CentOS 64位,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;
};
流在其他地方被初始化和销毁,但本质上它们仍然"永远"开放供写入。
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无内存可用缓存缓冲区
相关文章:
- 从构造函数抛出异常时如何克服内存泄漏
- malloc() 可能出现内存泄漏
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 尽管遵循了规则,内存泄漏在哪里
- 为什么调用堆栈数组会导致内存泄漏
- 在简单示例中,Python3 + ctypes 回调会导致内存泄漏
- 使用模板类的自定义列表类型中的内存泄漏
- 为什么以下C++代码中存在内存泄漏?
- OpenCV 我应该使用智能指针来防止内存泄漏吗?
- 我是否生成线程并导致内存泄漏?
- 多线程程序中出现意外的内存泄漏
- 为什么此函数会导致内存泄漏?
- 在 C++ 库中使用cythonized python时内存泄漏
- 需要帮助查找内存泄漏
- 瓦尔格林德的内存泄漏使用新的
- 无法找出我的代码中的内存泄漏
- C++ 结构内部的unordered_map会导致内存泄漏问题吗?
- 可视化 使用 VS Code 查找C++应用程序中的内存泄漏
- Shared_ptr双链接列表内存泄漏
- C++ 在类中使用常量引用文本时 O2 内存泄漏