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

标签 c malloc gtk3 free

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

相关文章:

c - 是否可以释放在 printf 内部调用的函数(仅)的返回值(在 c 中)?

c - Gtk+3 &C & Glade 问题

c - 如何优化 malloc() 或动态填充未知大小的内存?

linux - 值错误 : Namespace Gtk not available

python - 你如何在 Linux 中抓取选定的屏幕区域?

Python 使用 ctypes 传递参数,参数无效

c - 如何将信号传递给另一个进程?

c - 具有保序功能的 C 霍夫曼编码

c - 如何在 C 中分配连续的二维字符串数组

c - 通过 Malloc 增加分配给结构的内存大小