GTK+ is cross platform graphical user interface library previously known as GIMP (GNU image manipulation program) toolkit. it is most popular GUI library along with Qt(Nokia) GUI library in open source community. Linux Gnome desktop (ubuntu,fedora,centOs and may more) is best example of its uses, which is written in gtk.

For beginner go to this site and learn basic gtk programming. Before learning memory management in gtk we should note following facts:

  • All GTK objects inherit from the GObject class provided by library.
  • GOJect is used to provide object-oriented C-based APIs

For example to create button in gtk

               GtkWidget *mybutton;

               mybutton = gtk_button_new();

  • All widgets in gtk is reference counted objects and reference counted means number of owners of widget.
  • There are two types of reference counting in gtk library, floating and non floating.
  • GObject is base class and all gtk widgets are direct or indirect descendant of GObject.
  • The gtk widget which is direct descendant of GObject starts with reference count 1 and the widget which is indirect descendant of GObject starts with floating reference count 1.0 . Let us discuss how to handle reference count of gtk widget to avoid memory leak in gtk based program.

Object hierarchy


╰── GInitiallyUnowned

╰── GtkWidget

├── GtkContainer

├── GtkMisc

├── GtkCalendar

├── GtkCellView

├── GtkDrawingArea

├── GtkEntry

…………..see gtk reference for all objects

Most of gtk widgets are derived from GInitiallyUnowned object. some of gtk widgets are GObject that are not GInitiallyUnowned. for example below widgets are not derived from GInitiallyUnowned, they are direct descendants of Gobject.











Object memory management

the object has a floating ref, it converts that reference to a normal ref
else it increases the ref count by one

void g_object_unref (gpointer object);

This will decrease the reference count of object, if ref count == 0, the object is destroyed

The GObject library also provides the function g_object_is_floating() which checks whether an object has a floating reference and returns true if it does.

Sample program to check floating or not floating reference of gtk widgets

compile above program

gcc simple.c -o simple pkg-config --cflags --libs gtk+-3.0

output will be

window is not floating

fixed is floating

button is floating