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.
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.
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.
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 .
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.
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; }
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With