This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

Re: malloc/free & new/delete balance


| Can anyone think of any reasons other than these to use free?
| 
| 1) delete just calls free anyway, so this saves a function call.
| 
| 2) The standard doesn't absolutely specify using delete, so standard
| conforming programs must replace new[] and delete[] if they replace new
| and delete.  Therefore we should introduce hideous bugs into their code if
| they don't comply.

These are the two reasons I came up with too; and they would be
enough reason to keep the current call to free() if that wasn't
a bug:

1) The standards demands that the default delete[] reclaims storage
   allocated by a previous call to default new[].
2) The default new[] returns new, but NOT necessarily the default new.

While calling free() works for the egcs implementation of the
*default* `operator new(size_t)', it is no more then 'works'.
A coincident, because of how the default new of egcs is implemented.
In general it is not correct to call free() for a pointer allocated
with new.  Calling free() does NOT garantee that the call to delete[]
will reclaim the storage allocated by a previous call to default new[]
(it might just crash).

I think that the following code is valid C++, not invalidated by the
standard (ie: the standard does not demand to overload new[] and delete[]
when you overload new and delete):

void *operator new(size_t size)
{
  void *ptr = malloc(size + 2 * sizeof(size_t));
  if (ptr == NULL)
    return NULL;
  size_t *info = static_cast<size_t *>(ptr);
  info[0] = MAGIC_NUMBER;
  info[1] = size;
  return &info[2];
}

void operator delete(void *ptr)
{
  if (ptr == NULL)
    return;
  size_t *info = static_cast<size_t *>(ptr) - 2;
  free(info);
}

int main(void)
{
  char *p = new char[10];	// Calls default new[]
  delete [] p;			// Calls default delete[]
}

Which proves that delete[] calling free is not conforming to the
standard: It doesn't reclaim the storage allocated by the call
to new[], it crashes.

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


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]