Click here to Skip to main content
15,884,099 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i tried to overload the operator new in MFC and it didn't compile so i did #undef new but it still didn't work due to linker errors such as:

error LNK2005: "void * __cdecl operator new(unsigned __int64)" (??2@YAPEAX_K@Z) already defined in Database SoftwareDlg.obj

and

fatal error LNK1169: one or more multiply defined symbols found

C++
void* operator new(size_t size)
{
 return malloc(size);
}


What I have tried:

I tried #undef new but it still gave errors
Posted
Updated 5-Mar-20 6:36am

What you did was provide an alternate implementation of a function. That is not an override and it is why you get a link error.

The way MFC does this is by redefining new to DEBUG_NEW in every source module and then they provide an implementation of DEBUG_NEW. You need to do something similar. MFC's definition looks like this :
C++
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
so you need to do something like :
C++
#ifdef _DEBUG
#define new MyNew
#endif
and provide a prototype and a definition of that function. You could start with a variation of what you have there :
C++
void* operator MyNew( size_t size )
{
   return calloc( 1, size);   // calloc will set the memory to zero also
}
 
Share this answer
 
Comments
Rick York 5-Mar-20 11:28am    
That is why I wrote, "provide a prototype..." If it is undefined that means you have not provided a prototype for it so it will be defined.
I suggest that you read new Operator (C++) | Microsoft Docs[^], which shows how to create your own version of new. However, I notice that you say you are new to C++, so I think it better that you concentrate on the basics first.
 
Share this answer
 
operator new is defined in global namespace. Why do you need to define it? Is the default operator does not suit your needs?
 
Share this answer
 
Comments
Harasees_Singh 6-Mar-20 2:56am    
@steveb I want to know how much heap memory and program initializes and frees, so i can just overload the operator and add one more line of code to keep in track the memory i'm initializing or freeing

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900