如何在最简单的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();
}

您可以尝试:

int main()
{
Fl_Window *window = new Fl_Window(win_w, win_h, "Hello, World!");
window->end();
window->show();
int retval = 1;
if (Fl::run())
retval =0;
delete window ;
return retval ;
}

相关内容

  • 没有找到相关文章

最新更新