gpt4 book ai didi

c - 如何正确(有效地)释放 gtk 小部件中的内存

转载 作者:太空狗 更新时间:2023-10-29 17:22:14 26 4
gpt4 key购买 nike

我正在尝试了解在完成 GTK 小部件时如何正确释放内存,例如,如果我需要创建和销毁许多小部件。但是,无论我尝试什么,valgrind 似乎都表明存在内存泄漏。我查看了其他问题,包括列出 GTK 的 valgrind 抑制文件的问题,但它并没有改变结果。

这是重现我的问题的最简单的代码片段:

#include "gtk/gtk.h"

int main()
{
GtkWidget * widget = gtk_fixed_new();
g_object_ref(widget);
g_object_ref_sink(widget); // remove floating reference, and own this object ourselves

g_object_unref(widget);

gtk_widget_destroy(widget);
}

我的期望是(在处理 float 引用之后)unref() 函数应该将引用计数减少到零,然后释放所有内存。我把 gtk_widget_destroy() 放在那里是为了更好地衡量,但我不确定它是否真的有必要(而且它不会改变泄漏的程度)。

问题 Memory Leaks in GTK hello_world program 的 valgrind 命令 G_SLICE=debug-blocks valgrind ./t3 --supression=~/Downloads/GNOME.supp 的输出是

==10079== HEAP SUMMARY:
==10079== in use at exit: 164,338 bytes in 847 blocks
==10079== total heap usage: 1,380 allocs, 533 frees, 219,176 bytes allocated
==10079==
==10079== LEAK SUMMARY:
==10079== definitely lost: 0 bytes in 0 blocks
==10079== indirectly lost: 0 bytes in 0 blocks
==10079== possibly lost: 21,350 bytes in 174 blocks
==10079== still reachable: 142,988 bytes in 673 blocks
==10079== suppressed: 0 bytes in 0 blocks
==10079== Rerun with --leak-check=full to see details of leaked memory

我看过的其他文档是 http://www.demko.ca/blog/posts/200705_gtkmm_refcoutning.txthttps://developer.gnome.org/gtk2/2.24/GtkObject.html

你可以编译我的片段

gcc -std=gnu99 `pkg-config --cflags gtk+-2.0` t3.c -o t3 `pkg-config --libs gtk+-2.0 gthread-2.0`

有人知道我错过了什么吗?我应该调用另一个函数来确保释放内存吗?

最佳答案

 - g_object_ref

Increases ref count by one

- g_object_unref

Decreases ref count by one, if ref count == 0, the object is destroyed

- g_object_ref_sink

IF the object has a floating ref, it converts that reference to a normal ref (sinks it)
ELSE it increases the ref count by one

- All objects start with a floating ref count of 1

如需进一步阅读,我建议您阅读以下文章:Introduction to Memory Management in GTK+

现在,继续您的示例,让我们看看函数调用及其作用:

GtkWidget * widget = gtk_fixed_new(); //widget created with ref count of 1 | floating = true
g_object_ref(widget); // floating = true, ref count increased to 2
g_object_ref_sink(widget); // floating = false, ref count remains at 2

g_object_unref(widget); // floating = false, ref count decreases to 1

//No further unrefs, hello leak!

我希望这能解释你的漏洞,一定要阅读上面提到的文章。

关于c - 如何正确(有效地)释放 gtk 小部件中的内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17732598/

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