1

Hi this is a little complicated so please let me know if any of this does not make sense, our team is writing a C++ application and we have previously had operator new overloaded. Recently I ran into this article: http://www.flipcode.com/archives/How_To_Find_Memory_Leaks.shtml about how to get debug information with our memory allocations.

All the files within the application #include one file where we have compile-time platform configurations, and within that file I added the following:

#ifdef _DEBUG
void* operator new(size_t size, const char *filename, const char *funcname, int line);
void* operator new[](size_t size, const char *filename, const char *funcname, int line);
#define new new(__FILE__, __FUNCSIG__, __LINE__)
#endif

Since we only link libcmt.lib for our platform build, to use the STL I removed our old implementation of operator new which looked like:

// in a .cpp file:
void*
operator new(size_t size) { ... }

and replaced it with:

// in the same .cpp file as above...
#undef new
void* operator new(size_t size, const char *filename, const char *funcname, int line) { ... }
#define new new(__FILE__, __FUNCSIG__, __LINE__)

this works fine for compiling, but I'm getting a bunch of linker errors from libcmt.lib:

ex: libcmt.lib(malloc.obj) : error LNK2001: unresolved external symbol __imp_HeapAlloc

Adding back the old implementation of operator new (without the additional parameters) allows the linker to link everything successfully.

My question: I want libcmt to see my macro (#define new new(FILE, FUNCSIG, LINE)) and thus when it links try and link the version I defined (with the debug macros).

How do I get this to work?? (I also tried using the property sheets within visual studio to define the macro)

Short
  • 7,767
  • 2
  • 25
  • 33
  • 2
    I think the library won't link because it wasn't compiled with your overloaded `new` operator. Just defining an overloaded `new` in your own code won't magically make it appear in the pre-built library. – dreamlax Nov 29 '12 at 21:39
  • 3
    As @dreamlax said, this won't work. It's a Microsoft hack in MFC that should be taken out and shot. Writing a macro whose name is a keyword produces undefined behavior if that keyword is used after the macro is defined. – Pete Becker Nov 29 '12 at 21:45
  • 2
    @PeteBecker I would prefer a good old-fashioned biblical stoning myself. – WhozCraig Nov 29 '12 at 22:02

1 Answers1

4

You can't get it to work. If this macro is defined in any file that includes a standard header, the behavior is undefined. And of course, normal evolution of a project will lead people to define class local operator new, or use placement new, or any one of a number of techniques which this macro will break. It's on about the same level as #define while if. Redefining a keyword in a macro is a sure way of getting into trouble, even if you don't use the standard library.

James Kanze
  • 150,581
  • 18
  • 184
  • 329