2

I have overloaded new and delete operators. I want to save pointers to 'old' new and delete to call it into 'new' new and delete. For example:

#include "h.h"
void * operator new ( size_t size, /*args*/ ) throw (std::bad_alloc)
{
    void * p = 0;
    p = original_new(size); //calling for 'old' new
    //some code
    return p;
}

And the similar operator delete.

So, I'm trying in my header file to type the following:

static void * (*original_new)(size_t) = ::operator new;
static void * (*original_new_arr)(size_t) = ::operator new[];
static void (*original_delete)(void *) = ::operator delete;
static void (*original_delete_arr)(void *) = ::operator delete[];

It is successfully compiled, but I have core dump on start. It is possible to call malloc in new bad it is really bad idea. It is possible to call new(std::nothrow) but it is bad too.

Unihedron
  • 10,902
  • 13
  • 62
  • 72
Jury
  • 1,227
  • 3
  • 17
  • 30

1 Answers1

2

You don't need to save pointers; defining a placement new operator (any operator new function which takes more than one argument) doesn't remove the existing operators; it just overloads them. To call the standard operator new function from a placement operator new function:

p = ::operator new( size );

Note that you do not want to do this if your placement new returns anything but the exact address returned by ::operator new. Otherwise, delete won't work. If you use any placement new that return anything other than a pointer returned by ::operator new, you need to define a new global operator delete (because this is the one that will be called), which in turn means that you have to define a new standard operator new as well, so that it will work correctly with your new operator delete. In order to avoid having to implement all of the memory management yourself, use malloc and free in your implementations.

James Kanze
  • 150,581
  • 18
  • 184
  • 329
  • I have big project with memory leaks, I don't want to modify code a lot. Now, if I `inlude "h.h"` in cpp file it obtains a redefined `new` and `delete`, if I don`t include - it uses 'old' operators. You are right. But, it seems impossible to overload `operator delete(void *p)` to `operator delete(void *p, char *file, int line)`. So, calling 'old' `delete` from 'new' `delete` is infinite recursion. – Jury Dec 19 '11 at 11:02
  • Replacing global standard new and delete doesn't require any changes in your code, or even recompiling; all you have to do is ensure that your new versions come before the standard library in the list of files to be linked. With regards to `delete`, you can (and should) define a placement delete if you define a placement new. But most of the time, it will still be the standard delete which is called, so if you have a special new, you have to provide a non-placement delete as well to handle it, and if you define a non-placement delete, you have to define the non-placement new as well. – James Kanze Dec 19 '11 at 13:32