c++fltk

Memory leak after button execution callback function in C++ library FLTK


Compile the following code

#include<FL/Fl.H>
#include<FL/Fl_Window.H>
#include<FL/Fl_Box.H>
#include<FL/Fl_Button.H>
#include<FL/fl_ask.H>

#include<bits/stdc++.h>
using namespace std;

int main(int argc,char *argv[]){
    auto window = make_unique<Fl_Window>(500,300);
    auto box = make_unique<Fl_Box>(20,40,260,100,"Hello world");
    box->box(FL_UP_BOX);
    box->labelsize(20);
    box->labelfont(FL_BOLD+FL_ITALIC);
    box->labeltype(FL_SHADOW_LABEL);

    auto btn = make_unique<Fl_Button>(20,200,100,50,"btn");
    btn->callback((Fl_Callback*)[](Fl_Widget *w,void *v)->void{
        fl_alert("btn callback");
    });

    window->end();
    window->show(argc,argv);
    
    return Fl::run();
}

When you click on the btn button several times you can see that the memory used by the fltk window program is increasing and not being freed.

I want the memory to be reduced to what it was after fltk_alert pops up


Solution

  • Short answer: this is not a memory leak.

    Long answer: it would only be a leak if the memory size increased every time you click on the button. What I see is different:

    Tested on Linux.

    Explanation:

    1. FLTK allocates some structures or uses some library functions that allocate structures like fonts when for instance a font is used for the first time. This memory is not free'd immediately because this would be very wasteful (the same font can - and will often - be used over and over again).

    2. All memory allocated in such operations is returned to the system when the program exits.