Question

I'm making a little memory leak finder in my program, but my way of overloading new and delete (and also new[] and delete[]) doesn't seem to do anything.

void* operator new (unsigned int size, const char* filename, int line)
{
    void* ptr = new void[size];
    memleakfinder.AddTrack(ptr,size,filename,line);
    return ptr;
}

The way I overloaded new is shown in the code snippet above. I guess it's something with the operator returning void* but I do not know what to do about it.

1
24
9/15/2017 9:11:39 PM

Accepted Answer

void* ptr = new void[size];

Can't do that. Fix it.

Never ever try to overload new/delete globally. Either have them in a base class and derive all your objects from this class or use a namespace or a template allocator parameter. Why, you may ask. Because in case your program is more than a single file and using STL or other libraries you are going to screw up.

Here's a distilled version of new operator from VS2005 new.cpp:

void * operator new(size_t size) _THROW1(_STD bad_alloc)
{       // try to allocate size bytes
   void *p;
   while ((p = malloc(size)) == 0)
    if (_callnewh(size) == 0)
     {       // report no memory
        static const std::bad_alloc nomem;
        _RAISE(nomem);
     }

     return (p);
}
6
2/24/2009 6:55:06 PM

RE:

Never ever try to overload new/delete globally

Why is it whenever someone try's to use a less common feature of C++, someone acts like it should never be done?

It's done all the time, it is quite common, and I have not worked for company that did not do this.

Globally overloaded new and delete are extremely helpful in tracking memory, memory bugs, buffer overruns, etc.

Nobody in their right mind is going to go through a program with several million lines of code, and add a new and delete member to each and every class. That's just stupid.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon