While trying to track and prepare for memory of my own memory manager, I tried to override the new statement. The flip code article was my main guide in this process ( http://www.flipcode.com/archives/How_To_Find_Memory_Leaks.shtml ).
After implementing the methods described in this article, I remain with the problem that somewhere in the STL "crtdbg.h" is included directly or indirectly through some of the header files that are included (using Visual Studio 2010).
This will result in an error:
[...]10.0\vc\include\crtdbg.h(1078): error C2365: 'operator new' : redefinition; previous definition was 'function' [...]10.0\vc\include\crtdbg.h(1078): error C2078: too many initializers [...]
Performing a quick check by placing "_CrtDumpMemoryLeaks ()" without including header files confirms my suspicion that the header files are indeed included in the STL files.
Leaving aside, even if it is a good idea or not to implement my own new / delete, I wonder how I can have my own new / removed implementations, still using some standard library functions and not having these override errors.
The code is as follows:
memdebug.h
#ifndef _MEM_DEBUG_H #define _MEM_DEBUG_H #ifdef _DEBUG void * operator new( unsigned int size, const char *filename, int line ); void operator delete( void *ptr ); #define DEBUG_NEW new(__FILE__, __LINE__) #define new DEBUG_NEW #endif #endif
memdebug.c
#ifdef _DEBUG void * operator new( unsigned int size, const char *filename, int line ) { void *ptr = (void *)malloc(size);
main.cpp
#include "memdebug.h" #include <iostream> void main() { Test *pTest = new Test(); std::cout << "end" << std::endl; }
How I solved this by moving #define new DEBUG_NEW below <iostream> ; The problem is resolved because it will not rewrite the new in crtdbg.h ; however, it does make it difficult to make sure that it always runs after possible headers containing the crtdbg.h file.
I believe that this can only be solved with a custom name for the new operator and use it instead. Am I right?