caillon.blog

GSource and You

If you maintain a GNOME package, you might want to grep for "\bGSource\b" in your source tree. If you find any of these, chances are you are probably leaking. I've already found 4 GNOME packages that leak using this technique, and had to school jrb on this a bit ago (hopefully he doesn't mind me using him as an example), so don't feel bad if your package has this leak.

Bad (leaks)

GSource *source; source = g_timeout_source_new (); /* Refcount is at 1 */ g_source_set_callback (source, my_source_callback, NULL, NULL); g_source_attach (source, NULL); /* Refcount is now at 2 */

When the GSource is removed from its GMainContext, because the timeout executed, or because g_source_destroy () was called on it, etc. the refcount will be dropped back down to 1, and it will hang around in memory. Make sure to call g_source_unref (source) on your GSource after attaching it to the GMainContext, like so:

Good (doesn't leak)

GSource *source; source = g_timeout_source_new (); /* Refcount is at 1 */ g_source_set_callback (source, my_source_callback, NULL, NULL); g_source_attach (source, NULL); /* Refcount is now at 2 */ g_source_unref (source); /* Refcount back down to 1 */