I have the following string class that inherits from MFC CString
class TString : public CString
{
public:
TString() : CString(_T(""))
{
}
TString(LPCTSTR str) : CString(str)
{
}
};
I had an out of memory exception in a method that used the + operator with TString frequently, so I tried to make a test like the following
TString str;
TCHAR buffer[] = "Hello world, Hello world, Hello world, Hello world, Hello world, Hello world";
uint i = 0;
while(i++ < 100000000)
{
str = buffer;
str += buffer;
}
that took a lot of memory and ended with out of memory exception this is a shot for the memory change from the task manager after the last code was executed
when I replaced the TString with the CString it was normal took the time and no out of memory exception and the memory was stable in task manager as in this shot
I tried the following 2 states
- I created another exe application that depend on the same Library that contain the TString class it worked very fine like CString
- I caled Sleep(1) inside the while loop and it gave to rapid change in the memory and was stable also What can I do to fix such a problem??
EDIT:
There were some wrong in my explanation when I recompiled the solution CString also had the same behaviour even the std::string I thought the new operator overloading I created a custom class that call the malloc and free at the destructor it also lead to the same behaviour, I moved that test code to the first entry point in my application to constructor of my application that inherits from CWinAppEx the code worked fine then I looked at the InitInstance I found a memory leak detection 4 lines of code as the following
int tmpDbgFlag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
tmpDbgFlag |= _CRTDBG_DELAY_FREE_MEM_DF;//<====this is the evil after comment everything is fine
tmpDbgFlag |= _CRTDBG_LEAK_CHECK_DF;
_CrtSetDbgFlag(tmpDbgFlag);
I always know that it's a human mistake. That cause disasters.
I just commented the line
tmpDbgFlag |= _CRTDBG_DELAY_FREE_MEM_DF;
That solved it. this answer also talk about the usage of this flag Finding heap corruption I thank everyone tried to help in this problem, I hope that it will help.