Re: GTK+ and memory allocation
- From: Michael Torrie <torriem gmail com>
- Cc: Gnome List <gtk-list gnome org>
- Subject: Re: GTK+ and memory allocation
- Date: Sun, 28 Jun 2009 21:01:18 -0600
joshua rh comcast net wrote:
> GtkWidget widget;
>
> &widget = gtk_window_new(GTK_WINDOW_TOPLEVEL);
I don't believe this is valid C Code. You can't take a static variable
and change its address! gtk_window_new allocates a new GtkWindow object
on the heap, increases its ref count to 1 and returns a pointer to it.
> and what if you have this:
>
> GtkWidget *widget;
>
> widget = gtk_window_new(GTK_WINDOW_TOPLEVEL);
This is the way you have to do it. As the function name implies, this
allocates a new window. If you want to get rid of it, you have to unref
it which, when the ref count drops to zero, will cause it to be freed.
If you don't you'll have a memory like. This is pretty standard in C.
Of course sometimes an API call gives you a pointer (reference to an
object) but you don't need to free it when you're done because someone
else will.
Once you've programmed a bit in C, these things all become second
nature. When using glib calls, I find it's very handy to create glib
structures with callbacks for freeing the elements of the structure.
For example, if I create a hash table, I create it with a pointer to a
function that can free each node. That way I just have to call the API
call to destroy the list and it takes care of the nodes too (kind of
like how a destructor in C++ works).
[
Date Prev][
Date Next] [
Thread Prev][
Thread Next]
[
Thread Index]
[
Date Index]
[
Author Index]