Click here to Skip to main content
15,946,074 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hi,
I am checking for memory leaks in my MFC SDI app, in the OnBnClickedOK() method for one of my dialogs.
I have tracked down a memory leak to be due to the GetWindowText line in my code below.

void CMyDlg::OnBnClickedOk()
{
		CWnd* pWnd = GetDlgItem(IDC_EDIT1);

		CString sequenceName;

		pWnd->GetWindowText(sequenceName);


Can anyone please tell my why the leak occurs. I am using CMemoryState to check for memory leaks, as shown below, and diffMemState.m_lCounts[1] has a value of 1.

#ifdef _DEBUG
   newMemState.Checkpoint();
   if( diffMemState.Difference( oldMemState, newMemState ) )
   {
	TRACE("Memory leaked!\n" );
      	AfxMessageBox(L"Memory leaked!\n" );
   }
#endif
		pWnd->GetWindowText(sequenceName);
#ifdef _DEBUG
   newMemState.Checkpoint();
   if( diffMemState.Difference( oldMemState, newMemState ) )
   {
	TRACE("Memory leaked!\n" );
	AfxMessageBox(L"Memory leaked!\n" );
   }
#endif
Posted
Comments
Albert Holguin 12-Dec-11 13:11pm    
You're not checking this right... as Jack states in his solution, you can't even check these things until they go out of scope. Your test is not valid.

1 solution

C++
pWnd->GetWindowText(sequenceName);

Allocates memory in the CString which won't be freed until the string goes out of scope..

CString (varies with version) uses pointer sharing and delayed garbage collection.

So it's possible that the memory may hang around a while even after it goes out of scope.

Memory Leak detection won't necessarily be valid until your program is closing.

******


Put the following macros in every CPP file after your header includes.

C++
#ifdef _DEBUG
#define new DEBUG_NEW
#endif


This will allow the debugger to track every memory allocation and if you have leaks will show you those locations (in the output window) when the program exits.
 
Share this answer
 
v2
Comments
Albert Holguin 12-Dec-11 13:23pm    
I mostly agree with you... +4
JackDingler 12-Dec-11 13:53pm    
What don't you agree with?

I'm always interested in learning new things.
Albert Holguin 12-Dec-11 15:44pm    
Well, for one, there's no such thing as garbage collection in C++... CStrings use reference counting.
JackDingler 12-Dec-11 15:52pm    
Good answer on reference counting, the current implementation does use reference counting.

But I could quibble with you on Garbage Collection.

C++ doesn't make it impossible to implement. I've done it.
Albert Holguin 12-Dec-11 23:58pm    
Well, just about anything is possible if you make it yourself, not the point. There's no garbage collector in C++ or MFC.

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