Take the 2-minute tour ×

guys, If I override the global new and delete in my dll code, will this override the user code new and delete? I made a test, and it shows the user new and delete will not be impacted. If I want to make user code new and delete be replaced by mine sdk new/delete, how to do that.

What's the case of template class. Template class definition includes some new/delete. And user code might instantiate it. Then, it might use user new/delete, right?

share|improve this question
I'm not sure you can do this that way. Tools like valgrind do it, I believe, by replacing the native new and delete functions by their own version, substituting the native library with their own. –  ereOn Apr 27 '11 at 9:36
A related question by the OP here. –  razlebe Apr 27 '11 at 10:14

4 Answers 4

up vote 3 down vote accepted

No, on Windows each DLL has its own operator new()/operator delete(). However you should be careful - if some DLL news an object that object should be deleted using the same operator delete() - otherwise you run into undefined behavior.

share|improve this answer
What's the case of template class. Most of template class defines their behavior in header file. Then might get instantiate in user code... –  giggle Apr 27 '11 at 10:10
@giggle: If there's a slightest risk that template will be instantiated on both sides you might run into undefined behavior. If it's surely instantiated on one side only you're fine. –  sharptooth Apr 27 '11 at 10:34
does this also work if dll A exports the global new and delete operators, and dll B uses dll A? Won't B then use A's new and delete? –  stijn Apr 27 '11 at 11:05

It won't unless your new/delete functions are declared in the user code.

share|improve this answer

One way to do it is have your DLL apply API hooks to the EXE when it the DLL is loaded. Then whenever the EXE calls one of the memory allocation functions (e.g. HeapAlloc), it gets transferred to your code. There are a few memory allocation APIs, so get them all, or just get whichever the new/delete operators use (most likely HeapAlloc/HeapFree).

Not orthodox maybe, but if you want to do what you say .. that is a way. If you have access to the source code of both the EXE and DLL there are likely better solutions though.

share|improve this answer


Overload the new and delete operator in Global Scope or class scope(of the user code), as per your need.

Just by overloading new and delete in your own dll wont overload the user code versions. They will have to be speciically overloaded in their own scope.

share|improve this answer
You mean we could add a new/delete declaration and implementation in header file, and make user include this header file? –  giggle Apr 27 '11 at 10:14
@giggle: Yes, Please check overloading new and delete operators in any good C++ book. –  Alok Save Apr 27 '11 at 10:46

Your Answer


