首页 > 解决方案 > 如何修复最简单的 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 中的内存泄漏是否正常?如果没问题,如果程序已经连续运行了很长时间,为什么这不会导致问题呢?

标签: c++memorymemory-managementmemory-leaksfltk

解决方案


正如@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();
}

推荐阅读