Avoiding memory leaks with GtkTreeView

This is something I noticed playing around in valgrind and seems to be quite common in GTK+ code. When you retrieve a string from a GtkTreeView, YOU are responsible for freeing it:


gchar* my_string
gtk_tree_model_get (model, COLUMN_MY_STRING, &my_string, -1);
g_message ("Printing my string: %s", my_string);
/* Do something more useful
------------------------------- */
g_free (my_string); // Important, otherwise YOU leak memory.

In the hope it is correct and helps some people…

Commentary

Leave a response »

  1. 1. September 2nd, 2007

    Hi Johannes,

    it is possible to scan gnome-svn for such code fragment?
    Maybe, we can start a gnome-goal to fix that.

    bjoern
  2. 2. September 2nd, 2007

    hmm, might be difficult to do this in an automated way as there might be a lot of code depending on the string before I can be free’d. But maybe some grep wizards might even be able to do this. Anyway, I think it’s better to check your code with valgrind to fix those (and other bugs). This also gives you hints on invalid reads/writes.

  3. 3. September 2nd, 2007

    Strictly speaking, you free all memory you get from gtk_tree_model_get(). So you free strings, unref objects, unref boxed types, and so on. Obviously literal pointers and integer types don’t need any special work.

    Ross
  4. 4. September 3rd, 2007

    Or just use gtkmm. :-P

  5. 5. September 4th, 2007

    Shouldn’t a valgrind plugin of some sort be able to detect that ?

    Thomas

Trackbacks

Leave a comment, a trackback from your own site or subscribe to an RSS feed for this entry. Trackback URL for this entry Comments feed for this entry

Leave a response

Leave a URL

Preview