Search code examples
c++gtkmmgtk4

segmentation fault when trying to set a button's label inside a lambda function


I've been trying to learn gtkmm4, but I've run into a strange runtime error

My Code:

#include <gtkmm.h>
#include <iostream>

class MyWindow : public Gtk::Window
{
public:
    MyWindow();
};

MyWindow::MyWindow()
{
    set_title("Basic application");
    set_default_size(200, 200);
    
    Gtk::Button button("Hello World");
    button.set_label("test");
    button.signal_clicked().connect([&button]() -> void {
        button.set_label("testing!");
    });

    set_child(button);
}

int main(int argc, char* argv[])
{
    auto app = Gtk::Application::create("org.gtkmm.examples.base");

    return app->make_window_and_run<MyWindow>(argc, argv);
}

The error:

[1]    183029 segmentation fault (core dumped)

This error occurs when I click on the button.


Solution

  • You have a dangling reference to the local Gtk::Button variable, which is deconstructed at the completion of MyWindow's constructor. Try making button a member variable of your MyWindow class.