声明 gchar 后是否需要 g_free?

is g_free needed after declaring gchar?

我是初学者,使用 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;
}

到目前为止,我假设 malloc() 需要 free(),阅读 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()?这一点很重要的原因是因为在搜索中输入的每个字符都会调用此代码数千次。

那里的指针被释放,因为 gtk_tree_model_get mallocs 指向字符串的指针,并将提供的指针设置为指向这些字符串。 function reference

注意"Values with type G_TYPE_STRING need to be freed"

是的。

来自 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 的指针分配给 "return" 内存返回给你。然后您以 *str_data.

的形式访问字符串
void get_tree_model_get_simplified(g_char** str_data)
{
    *str_data = g_malloc(...);
}