gpt4 book ai didi

c - 声明 gchar 后是否需要 g_free?

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

我是初学者,使用 GTK+ 和 C 来编写一个小应用程序。我正在为 GtkTreeView 设置一个过滤器,显示功能如下,主要是从 here 复制的.

static gboolean filter_func (GtkTreeModel *model, GtkTreeIter *row, gpointer data) {
// if search string is empty return TRUE

gchar *titleId, *region, *name;
gtk_tree_model_get (model, row, 0, &titleId, 1, &region, 2, &name, -1);

// get search string
if (strstr (titleId, "search text here") != NULL) {
return TRUE;
}

g_free (titleId);
g_free (region);
g_free (name);

return FALSE;
}

到目前为止,我假设 free() 需要与 malloc() 一起阅读 https://developer.gnome.org/glib/stable/glib-Memory-Allocation.html告诉我:

It's important to match g_malloc() (and wrappers such as g_new()) with g_free()

如果是这样的话,为什么要在这里调用 g_free() 呢?这一点之所以重要,是因为在搜索中输入的每个字符都会调用此代码数千次。

最佳答案

是的。

来自 the docs .

Returned values with type G_TYPE_OBJECT have to be unreferenced, values with type G_TYPE_STRING or G_TYPE_BOXED have to be freed. Other values are passed by value.

G_TYPE_STRING 是“对应于以 nul 结尾的 C 字符串的基本类型”,即 gchar

the docs 中的“从 GtkTreeModel 读取数据”示例说得很清楚。

   gchar *str_data;
gint int_data;

// Make sure you terminate calls to gtk_tree_model_get() with a “-1” value
gtk_tree_model_get (list_store, &iter,
STRING_COLUMN, &str_data,
INT_COLUMN, &int_data,
-1);

// Do something with the data
g_print ("Row %d: (%s,%d)\n",
row_count, str_data, int_data);
g_free (str_data);

So if that is the case, then why is g_free() being called here?

因为 gtk_tree_model_get 正在为您执行 malloc。是a common use of a double pointer将函数内部分配的内存传递给调用者。

str_data 作为 g_char** 传递给 gtk_tree_model_get,因此它可以修改 str_data 指向的位置。 gtk_tree_model_get 分配内存,得到一个g_char*。它将该指针分配给 *str_data 以将内存“返回”给您。然后以 *str_data 的形式访问该字符串。

void get_tree_model_get_simplified(g_char** str_data)
{
*str_data = g_malloc(...);
}

关于c - 声明 gchar 后是否需要 g_free?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48613079/

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