[Gc] GC as a pointer registry

andsebjo at student.matnat.uio.no andsebjo at student.matnat.uio.no
Thu Mar 10 08:27:17 PST 2005

I'am doing some work where I need to verify if a pointer points to a valid
object or not. This is thought solved by using a GC to keep track of the
objects. Some time ago I posted a request for this, and was recommended to
use GC_base and/or GC_find_header. The idea is that the function
GCpointerCheck(ptr) should return 0 (not valid pointer) when a pointer
'ptr' has been freed.

By compiling and running the example below GC_base and GC_file_header
returns as if the pointer still points to a valid object, even though the
memory allocated to the pointer has been freed. Any idea of why this does
not work or how this problem can be solved? Thank you in advance for all

My GC version is 6.4, I configured  it using configure with no options and
make with no options.

#include "gc.h"
/** A function which returns true (1) or false (0) depending on some
integrity tests */

GCpointerCheck (void *ptr)
  int isvalid = 1;      // assume true to start

  // Run some checks to see if this pointer is valid
  if (NULL == ptr)
      isvalid = 0;      // NULL pointers are never good
  else if (GC_base (ptr) != ptr)
      //tests whether you have a pointer to beginning of an object
      //if not it is not valid
      isvalid = 0;
  else if (GC_find_header (ptr) == 0)
      //distinguish GC_-pointers from other valid pointers
      //if null
      isvalid = 0;
  return isvalid;

int main ()
  GC_find_leak = 1;
  int *p[10];
  int i;
  for (i = 0; i < 10; ++i)
      p[i] = GC_malloc (sizeof (int) + i);

  for (i = 1; i < 10; ++i)
      GC_free (p[i]);
      if (GCpointerCheck (p[i]) == 1)
        printf ("p[%i] pointer is a valid GC pointer.\n",i);
        printf ("p[%i] pointer is not a valid GC pointer.\n",i);
  return 1;

Andreas Saebjoernsen

PS! I am sorry if this message was send twice. It bounced as I did the
mistake of sending it from a different account than the one I subscribe
from, so I resend it.

More information about the Gc mailing list