我正在尝试使用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本身会分配一堆内存,而我却失去了需要做的事情。我虽然在g_object_unref
上执行GtkApplication
足以递归地释放与该GtkApplication
相关联的所有窗口的所有窗口小部件。我错了吗 ?
我应该怎么做才能避免内存泄漏?谢谢你的帮助。
答案 0 :(得分:4)
您的代码是正确的,几乎与文档演示中的代码相同。
GTK和GLib为缓冲区,它们自己的内存管理等分配内存.Valgrind报告的内容不太可能是内存泄漏,因为在执行应用程序期间使用了这个内存,并且在应用程序退出时没有释放但是留给了操作系统清理。这似乎是Valgrind的内存泄漏。抑制文件可用于帮助消除误报。
运行应用程序时,Glib和GTK有各种选项here来帮助调试。您可能想要查看G_SLICE环境变量。您可能会发现enter link description here对页面底部附近的抑制文件信息很有用。