c++ - 如何修复最简单的 FLTK 程序中的内存泄漏?
问题描述
我在使用 FLTK 的 C++ 程序中遇到了内存问题。在第一种情况下:
#include <Fl/Fl.H>
#include <Fl/Fl_Window.H>
enum {
win_w = 640,
win_h = 480,
btn_w = 80,
btn_h = 30
};
int main()
{
Fl_Window *window = new Fl_Window(win_w, win_h, "Hello, World!");
window->end();
window->show();
return Fl::run();
}
valgrind
说:
HEAP SUMMARY:
==2746== in use at exit: 711,091 bytes in 846 blocks
==2746== total heap usage: 13,330 allocs, 12,484 frees, 2,751,634 bytes allocated
==2746==
==2746== LEAK SUMMARY:
==2746== definitely lost: 0 bytes in 0 blocks
==2746== indirectly lost: 0 bytes in 0 blocks
==2746== possibly lost: 0 bytes in 0 blocks
==2746== still reachable: 711,091 bytes in 846 blocks
==2746== suppressed: 0 bytes in 0 blocks
==2746== Rerun with --leak-check=full to see details of leaked memory
如果我Fl_Button
在这个程序中添加一个,我们会有更多的内存泄漏。
...
Fl_Window *window = new Fl_Window(win_w, win_h, "Hello, World!");
Fl_Button *btn = new Fl_Button(win_w / 2 - btn_w / 2, win_h / 2 - btn_h / 2, btn_w, btn_h, "Button!");
window->end();
...
==2791== HEAP SUMMARY:
==2791== in use at exit: 1,065,964 bytes in 6,005 blocks
==2791== total heap usage: 25,233 allocs, 19,228 frees, 6,637,915 bytes allocated
==2791==
==2791== LEAK SUMMARY:
==2791== definitely lost: 5,376 bytes in 19 blocks
==2791== indirectly lost: 3,371 bytes in 128 blocks
==2791== possibly lost: 0 bytes in 0 blocks
==2791== still reachable: 1,057,217 bytes in 5,858 blocks
==2791== suppressed: 0 bytes in 0 blocks
==2791== Rerun with --leak-check=full to see details of leaked memory
一方面,这是正常的,因为我们没有释放内存。另一方面,这可以说是FLTK程序的一个经典例子。FLTK 中的内存泄漏是否正常?如果没问题,如果程序已经连续运行了很长时间,为什么这不会导致问题呢?
解决方案
正如@drescherjrn 所述,您可以在运行后删除窗口。就像是
int main()
{
Fl_Window *window = new Fl_Window(win_w, win_h, "Hello, World!");
window->end();
window->show();
int rv = Fl::run();
delete window;
return rv;
}
或者,C++ 有一个机制:auto_ptr ( http://www.cplusplus.com/reference/memory/auto_ptr/auto_ptr/ )
#include <memory>
int main()
{
std::auto_ptr<Fl_Window> window(new Fl_Window(win_w, win_h, "Hello, World!"));
window->end();
window->show();
return Fl::run();
}
推荐阅读
- python - 在熊猫数据框中正确左右对齐列
- powershell - 以编程方式删除 SharePoint 2013 回收站的内容
- c# - 我将 .NET CORE 项目从 2.1 更新到 3.1,但在 Startup 类中出现了一些错误
- ios - 如何在collection-view swift 5中更改动态行的颜色
- c# - C# 反射 - 从基类中获取超类的通用参数类型
- c++ - C++ 中的右值引用和一个简单的例子
- c++ - 在 C++ 中添加为字符串后打印字符
- python - RFC 5545 每天重复出现的问题
- python-3.x - 选择具有多级索引的特定行
- java - BufferedWriter 没有写入文件