Question

I am writing a program in C and using Gtk+ for the GUI. Everything works fine, but I have some doubts about possible memory leaks.

I need to show a list of elements and then filter this list by means of a search bar and buttons. I thought to use a GtkTreeView with a GtkListStore as described in this example.

When a filtering is performed I simply create a new GtkListStore and populate it with new elements and then set the new model in the GtkTreeView.

Do I need to free those models I am not using anymore or will Gtk+ automatically handle it?

Was it helpful?

Solution

Asserting you use gtk_tree_view_set_model to swap models.

docbook gtk_tree_view_set_model ()

void                gtk_tree_view_set_model             (GtkTreeView *tree_view,
                                                         GtkTreeModel *model);

Sets the model for a GtkTreeView. If the tree_view already has a model set, it will remove it before setting the new model. If model is NULL, then it will unset the old model.

So this means that if a model is associated with the view its referece counter will decrease by one (I actually verfied that by a look into the source, the documentation is not explicit enough here what "remove" means)).

If you handle it as the example says

   /* Create a view */
   tree = gtk_tree_view_new_with_model (GTK_TREE_MODEL (store));

   /* The view now holds a reference.  We can get rid of our own
    * reference */
   g_object_unref (G_OBJECT (store));

you do not need to do anything additionally unless you explicitly call g_object_ref or some other method which will add reference.

I strongly suggest you to get devhelp and install the Gtk+ docbook entries.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top