[Gc] Pointer References to GC heap

Sean Middleditch elanthis at awesomeplay.com
Thu Sep 23 10:54:15 PDT 2004

On Thu, 2004-09-23 at 19:25 +0200, Hans Oesterholt-Dijkema wrote:
> How does de GC collector detect that the pointers p
> and q are pointing to or not pointing to allocated
> memory? Does GC examine the stack?


> An other example: Suppose, glib is working with the
> GC_malloc and GC_free functions (which is possible).
>    GtkEntry *g=gtk_entry_new();
>    gtk_entry_set_text("Hi there");
>    {
>      gchar *t,*t1;
>         t=(char *) gtk_entry_get_text(g); // this function actually
>                                           // returns const gchar *!
>         t1=(char *) GC_MALLOC(strlen(t)+3);
>         strdup(t1,t);
>         strcat(t1,"!!");
>         gtk_entry_set_text(t1);
>         printf("%s\n",t);
>    }
> Note. gtk_entry_get_text() will internally allocate
> a new memory block for the text and store the contents 
> of t1 in this memory block *and* it will (GC_free) 
> the previous memory block. So, t would be pointng 
> to freeed memory.
> Will GC detect that t is still referencing the memory and
> not clean it up? (my recent experiences indicate different
> behaviour). Or must I leave out the GC_free function, so

No, it will not, because you've already freed the memory.  GC_free
instantly frees memory the exact same as a call to free() does.  t is
now referencing an invalid address, same as it would have before.

You will end up with a possible problem on subsequent allocations,
though - the GC will allocate some future block in the same area, and
then the GC will see that t points into it - possibly causing it to be
erroneously kept in memory longer than it should be.  Whenever you free
a pointer, *always* set it to NULL.  (That is expected practice even
when not using a GC.)  When you are done with a pointer, always set it
to NULL.  (And free the memory if you think that is appropriate at the

> that the memory of GtkEntry is explicitly left to the GC?
> Thanks in advance for your answers,
> --
> Hans Oesterholt-Dijkema
> _______________________________________________
> Gc mailing list
> Gc at linux.hpl.hp.com
> https://www.hpl.hp.com/hosted/linux/mail-archives/gc/
Sean Middleditch <elanthis at awesomeplay.com>
AwesomePlay Productions, Inc.

More information about the Gc mailing list