malloc/free & new/delete balance

Carlo Wood carlo@runaway.xs4all.nl
Mon Jun 29 08:41:00 GMT 1998


In gcc/cp/new2.cc,

WEAK(void * operator new[] (size_t sz) throw (std::bad_alloc))
{
  return ::operator new(sz);
}

...

WEAK (void operator delete[] (void *ptr) throw ())
{
  if (ptr)
    free (ptr);
}

This unbalance between calling `::operator new(size_t)' and `free(void *)'
is causing troubles when `operator new(size_t)' and `operator delete(void *)'
are overloaded [ for example to call special memory allocation/deallocation
functions called malloc_with_prepended_magic_number(size_t) and
free_with_prepended_magic_number(void *). Then calling 'operator
new[](size_t)' uses malloc_with_prepended_magic_number(size_t) and
'operator delete[](void *)' uses just free(void *) ].

The way it is now you force people to also overload operator new[] and
operator delete[] when they overloaded operator new and operator delete.

Imho, the only correct way is to balance this and use:

WEAK (void operator delete[] (void *ptr) throw ())
{
  ::operator delete(ptr);
}

Alternatively, and probably a little faster, is to duplicate the
code from operator new(size_t) and use:

WEAK(void * operator new[] (size_t sz) throw (std::bad_alloc))
{
  /*
   * This is an exact copy of
   * void * operator new (size_t sz) throw (std::bad_alloc)
   */

  void *p;

  /* malloc (0) is unpredictable; avoid it.  */
  if (sz == 0)
    sz = 1;
  p = (void *) malloc (sz);
  while (p == 0)
    {
      new_handler handler = __new_handler;
      if (! handler)
        throw bad_alloc ();
      handler ();
      p = (void *) malloc (sz);
    }

  return p;
}

Comments?

-- 
 Carlo Wood  <carlo@runaway.xs4all.nl>



More information about the Gcc mailing list