Click here to Skip to main content
15,888,521 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm using the CMemoryState to check for memory leaks as follows:

#ifdef _DEBUG
   		CMemoryState oldMemState, newMemState, diffMemState;
   		oldMemState.Checkpoint();
#endif

//put method to check in here

#ifdef _DEBUG
   		newMemState.Checkpoint();
   		if( diffMemState.Difference( oldMemState, newMemState ) )
   		{
			TRACE("Memory leaked!\n" );
      		        AfxMessageBox(L"Memory leaked!\n" );
   		}
#endif


Can somebody tell me how the struct is used to check for leaks. I have been looking at the members as I do my check and it seems that the only member in diffMemState that indicates a memory leak when it is non-zero is m_lCounts[1]. If any of the other m_lCounts[] are non-zero, it doesn't seem to mean that there is a memory leak - is that correct, and of so what do they mean?
Posted

1 solution

There is another useful call to add to your code,
diffstate.DumpStatistics();<br />
That should tell you of the things that remain allocated between the first checkpoint and the second checkpoint.

Now from previous notes, you should realize that not all "still allocated" objects / memory are "leaks". It might simply be some object that you are still using. For example, my application caches data read from a file. If I were to take the checkpoint before reading the data and then check for "leaks", the cached data would appear as "still allocated". Is that a "leak", no because I know about it and it was part of the design.

So use the "DumpStatistics" after your TRACE message to see what memory is still allocated. If you have the default DEBUG_NEW allocation, you should also see the module and line number where that memory was allocated. You might even be able to double-click on the output and Visual Studio should take you to the line where the allocation / new occurred.
 
Share this answer
 
Comments
JackDingler 14-Dec-11 17:44pm    
To try out the DEBUG_NEW macro...

1. Use the project wizard to create an MFC SDI or MDI Application.
2. Place the following code in the constructor for your document class.
new char[100];
3. Launch the application.
4. Close the application.
5. See the memory leak listed in the output pane.

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