0

I am a beginner using GTK+ with C to write a small app. I am setting up a filter for GtkTreeView, with the display func as below, mostly copied from 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;
}

I have assumed so far that free() is needed with malloc() and reading https://developer.gnome.org/glib/stable/glib-Memory-Allocation.html tells me:

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

So if that is the case, then why is g_free() being called here? The reason why this is important is because this code will be called thousands of times per character typed in the search.

Pablo
  • 13,271
  • 4
  • 39
  • 59
sprocket12
  • 5,368
  • 18
  • 64
  • 133

2 Answers2

5

Yes.

From 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 being "the fundamental type corresponding to nul-terminated C strings" which is gchar.

The "Reading data from a GtkTreeModel" example in the docs makes it very clear.

   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?

Because gtk_tree_model_get is doing the malloc for you. It is a common use of a double pointer to pass memory allocated inside a function to the caller.

str_data is passed to gtk_tree_model_get as a g_char** so it can modify where str_data points. gtk_tree_model_get allocates the memory, obtaining a g_char*. It assigns that pointer to *str_data to "return" the memory back to you. Then you access the string as *str_data.

void get_tree_model_get_simplified(g_char** str_data)
{
    *str_data = g_malloc(...);
}
Schwern
  • 153,029
  • 25
  • 195
  • 336
4

The pointers there are freed because gtk_tree_model_get mallocs pointers to strings and sets the pointers provided to point to those strings. function reference

Note where it says "Values with type G_TYPE_STRING need to be freed"

C_Elegans
  • 1,113
  • 8
  • 15