如何正确管理 GTK3 中的内存?

How to properly manage memory in GTK3?

我正在尝试使用 GTK3 在 C 中设置一个小项目。在 linux 64 位上编码,这是我设置的最小 Hello world 程序,灵感来自 documentation 本身。

#include <gtk/gtk.h>

static void
activate (GtkApplication* app,
          gpointer        user_data)   
{
    GtkWidget *window;
    GtkWidget *label;

    window = gtk_application_window_new( app );
    gtk_window_set_title( GTK_WINDOW( window ), "Minimal GTK" );
    gtk_window_set_default_size( GTK_WINDOW( window ), 400, 300 );

    label = gtk_label_new( "Some men just want to watch the world burn." );
    gtk_container_add( GTK_CONTAINER(window), label );

    gtk_widget_show_all( window );
}



int
main(int    argc,
     char **argv)
{
    GtkApplication *app;
    int app_status;

    app = gtk_application_new( "com.github.laerne.minimal_gtk", G_APPLICATION_FLAGS_NONE );
    g_signal_connect( app, "activate", G_CALLBACK(activate), NULL );

    app_status = g_application_run( G_APPLICATION(app), argc, argv );
    g_object_unref( app );

    return app_status;
}

很简单。有用。但是,当 运行 带有 valgrind 的 memcheck 模块的程序时,valgrind 会抱怨内存泄漏:

==11415== LEAK SUMMARY:
==11415==    definitely lost: 1,856 bytes in 4 blocks
==11415==    indirectly lost: 7,455 bytes in 320 blocks
==11415==      possibly lost: 4,899 bytes in 56 blocks
==11415==    still reachable: 1,809,562 bytes in 22,030 blocks
==11415==                       of which reachable via heuristic:
==11415==                         length64           : 6,240 bytes in 102 blocks
==11415==                         newarray           : 2,144 bytes in 54 blocks
==11415==         suppressed: 0 bytes in 0 blocks
==11415== Reachable blocks (those to which a pointer was found) are not shown.
==11415== To see them, rerun with: --leak-check=full --show-leak-kinds=all
==11415== 
==11415== For counts of detected and suppressed errors, rerun with: -v
==11415== ERROR SUMMARY: 42 errors from 42 contexts (suppressed: 0 from 0)

运行 --leak-check=full,我看到 GTK 自己分配了一堆内存,我不知道需要做什么。我虽然在 GtkApplication 上执行 g_object_unref 足以递归释放与 GtkApplication 关联的所有 windows 的所有小部件。我错了吗 ?

我应该怎么做才能避免内存泄漏?感谢您的帮助。

您的代码是正确的,并且与文档演示中的代码几乎相同。

GTK 和 GLib 为缓冲区分配内存,它们自己的内存管理等。Valgrind 报告的不太可能是内存泄漏,因为该内存在应用程序执行期间使用,并且在应用程序退出时没有释放,而是离开到OS收拾。这对 Valgrind 来说是内存泄漏。抑制文件可用于帮助消除误报。

Glib 和 GTK 有各种选项 here when running your application to help with debugging. You may want to look at the G_SLICE environment variable. You may find enter link description here 对页面底部附近的抑制文件信息很有用。