声明gchar后需要g_free吗?

spr*_*t12 0 c malloc free gtk3

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

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;
}
Run Code Online (Sandbox Code Playgroud)

我假定到目前为止这free()需要有malloc()和阅读https://developer.gnome.org/glib/stable/glib-Memory-Allocation.html告诉我:

重要的是要与g_malloc()(以及诸如的包装器g_new())进行匹配g_free()

因此,如果是这样,那么为什么g_free()在这里被称为?之所以如此重要,是因为对于搜索中键入的每个字符,此代码将被调用数千次。

Sch*_*ern 5

是。

文档

返回类型为G_TYPE_OBJECT的值必须是未引用的,类型为G_TYPE_STRING或G_TYPE_BOXED的值必须被释放。其他值按值传递。

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

在“ 从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);
Run Code Online (Sandbox Code Playgroud)

那么如果是这种情况,那么为什么在这里调用g_free()?

因为gtk_tree_model_getmalloc为您做。它是一个常见的使用双指针到功能到调用者分配内部存储器通。

str_data传递为gtk_tree_model_getg_char**因此可以修改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(...);
}
Run Code Online (Sandbox Code Playgroud)