[Gc] Determine the requested size of a memory block

Christian Gudrian christian at gudrian.org
Thu Apr 22 02:05:38 PDT 2010


Am 22.04.2010 09:43, schrieb Ivan Maidanski:

> In theory, it's possible to adjust hb_sz (returned by GC_size) to
> have a byte granularity (with some negligible performance loss).

I certainly do not want to fumble around in the innards of the collector.
Instead I now provide a custom implementation of the array new operator:

// -----------------------------------------------------------------
inline void * operator new[] (size_t size,
                              GCPlacement gcp,
                              GCCleanUpFunc cleanup = 0,
                              void * clientData = 0)
{
   size_t * ptr = (size_t *) ::operator new (size + sizeof (size_t), 
                                             gcp, cleanup, clientData);
   *ptr++ = size;
   return ptr;
}
// -----------------------------------------------------------------

The length() function looks like this:

// -----------------------------------------------------------------
template<class T>
size_t length (T * array)
{
   size_t * ptr = (size_t *) GC_base ( (void *) array);
   assert(ptr);
   return *ptr / sizeof (T);
}
// -----------------------------------------------------------------

Now it's possible to use arrays this way:

char * c = new (PointerFreeGC) char[123];
for (int i = 0; i < length(c); i++)
{
   char value = c[i];
   // ...
}

Christian


More information about the Gc mailing list