gpt4 book ai didi

c - 正确释放 GtkBuilder 对象

转载 作者:太空宇宙 更新时间:2023-11-04 02:27:33 24 4
gpt4 key购买 nike

我有以下 GTK+ 程序

////////////////////////////////////////////////////
// Example can be compiled with:
// gcc gui.c `pkg-config --cflags --libs gtk+-2.0`
//
// GUI file from glade must be in same folder from
// which the compiled binary is called.
////////////////////////////////////////////////////

#include <gtk/gtk.h>

int main(int argc, char *argv[]) {
GtkBuilder *gtkBuilder = gtk_builder_new();

gtk_init(&argc, &argv);

gtk_builder_add_from_file(gtkBuilder, "../gui.glade", NULL);

gtk_builder_connect_signals(gtkBuilder, NULL);

gtk_widget_show(GTK_WIDGET(gtk_builder_get_object(gtkBuilder, "main")));

g_object_unref(G_OBJECT(gtkBuilder));

// g_free(gtkBuilder);

gtk_main();

return 0;
}

和相应的 XML Glade 文件:

<?xml version="1.0" encoding="UTF-8"?>
<interface>
<requires lib="gtk+" version="2.24"/>
<!-- interface-naming-policy project-wide -->
<object class="GtkWindow" id="main">
<property name="width_request">400</property>
<property name="height_request">300</property>
<property name="can_focus">False</property>
<property name="default_width">690</property>
<property name="default_height">500</property>
<signal name="destroy" handler="gtk_main_quit" swapped="no"/>
<child>
<placeholder/>
</child>
</object>
</interface>

当我使用 Valgrind 编译并运行内存检查时,它会提示分配给 GtkBuilder 的内存可能 丢失了。当我取消注释 g_free() 指令时,我收到有关对 free() 的无效调用的错误。

我知道 GTK+ 框架本身有一些漏洞,即它不会在其整个生命周期内释放所需的资源。 GtkBuilder 是那些将被“泄露”的资源之一,还是有一种方法可以在没有 Valgrind 提示的情况下正确发布它?

最佳答案

在“取消引用”之后,由于您没有增加引用计数,即引用计数已降至 0,因此对象被释放。之后使用 g_free() 会报错。

来自documentation :

g_object_unref ()

void g_object_unref (gpointer object);

Decreases the reference count of object . When its reference count drops to 0, the object is finalized (i.e. its memory is freed).

If the pointer to the GObject may be reused in future (for example, if it is an instance variable of another object), it is recommended to clear the pointer to NULL rather than retain a dangling pointer to a potentially invalid GObject instance. Use g_clear_object () for this.

关于c - 正确释放 GtkBuilder 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48911820/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com