Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

overloading new/delete

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.

like image 430
Brammie Avatar asked Feb 24 '09 18:02

Brammie


People also ask

Can you overload delete new?

New and Delete operators can be overloaded globally or they can be overloaded for specific classes. If these operators are overloaded using member function for a class, it means that these operators are overloaded only for that specific class.

Why overload new and delete?

The most common reason to overload new and delete are simply to check for memory leaks, and memory usage stats. Note that "memory leak" is usually generalized to memory errors. You can check for things such as double deletes and buffer overruns.

What is new and delete operator in C++?

These operators allocate memory for objects from a pool called the free store (also known as the heap). The new operator calls the special function operator new , and the delete operator calls the special function operator delete .

Can I create new operators using operator overloading?

New operators can not be created. 2) Arity of the operators cannot be changed. 3) Precedence and associativity of the operators cannot be changed. 4) Overloaded operators cannot have default arguments except the function call operator () which can have default arguments.


2 Answers

Maybe you can do what you want with a little bit of preprocessor magic:

#include <iostream>  using namespace std;  void* operator new (size_t size, const char* filename, int line) {     void* ptr = new char[size];     cout << "size = " << size << " filename = " << filename << " line = " << line << endl;     return ptr; }  #define new new(__FILE__, __LINE__)  int main() {     int* x = new int; } 
like image 176
kyku Avatar answered Sep 23 '22 22:09

kyku


I think the problem here is that your new's parameter profile doesn't match that of the standard operator new, so that one isn't getting hidden (and is thus still being used).

Your parameter profiles for new and delete need to look like this:

void* operator new(size_t); void operator delete(void*, size_t); 
like image 30
T.E.D. Avatar answered Sep 22 '22 22:09

T.E.D.