GTK3 Memory leaks in Builder and gtk_init

Hello everyone. Faced a problem:
There are leaks when using the gtk_builder_add_from_file() and gtk_init() function;
g_object_unref() does not help in this case.
It starts on macOS Mojave

My code:

#include <gtk/gtk.h>

int mx_window_main(int argc, char **argv) {
    GObject *wnd_main;
    GtkBuilder *builder;

    system("leaks -q gui");         // No leaks
    gtk_init (&argc, &argv);
    system("leaks -q gui");         // First leak

    builder = gtk_builder_new();
    fprintf(stderr, "RETVAL: %d\n", gtk_builder_add_from_file(builder, MX_GUI_PATH, NULL));

    system("leaks -q gui");        // Rest leaks

    gtk_builder_connect_signals(builder, builder);
    wnd_main = gtk_builder_get_object (builder, "wnd_main");
    gtk_widget_show_all(GTK_WIDGET(wnd_main));
    gtk_main();
    return 0;
}

int main(int argc, char **argv) {
    mx_window_main(argc, argv);
    return 0;
}

Here is output


How do you advise getting rid of them?

1 Like

You cannot really detect leaks like this, with GTK (and its dependent libraries).

First of all, GTK will perform one-off allocations; these are not leaks by definition, as they are performed once, and they will be collected when the process terminates.

Additionally, GTK is using reference counting for most of its data structures; this means that resources will only be collected once their reference count drops to zero. For GtkBuilder, that happens when you explicitly call g_object_unref() once you’re done extracting all the widgets you care about. The ownership of the widgets created by GtkBuilder, though, is transferred to their parent container, and the ownership of the top-level GtkWindow is transferred to GTK itself. This is why calling g_object_unref() on the GtkBuilder instance does not seem to release memory: the resources allocated for each widget are owned by the top level window, and they will be collected when the window is closed.

1 Like

If you want to know more about the resource management of GObject-based libraries, you can read the related section of the GObject reference.

Additionally, I’d recommend using Valgrind to detect memory leaks and other memory issues; GLib and GTK can integrate with Valgrind and avoid false positives.

2 Likes

Thank you very much for your help. I hope this helps many of those people who come across this.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.