Click here to Skip to main content
Sign Up to vote bad
good
See more: C++MFC
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 14 Dec '11 - 10:44


1 solution

There is another useful call to add to your code, diffstate.DumpStatistics();
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.
  Permalink  
Comments
JackDingler - 14 Dec '11 - 17:44
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)

  Print Answers RSS
Your Filters
Interested
Ignored
     
0 Sergey Alexandrovich Kryukov 414
1 Arun Vasu 253
2 OriginalGriff 200
3 CPallini 163
4 Aarti Meswania 158
0 Sergey Alexandrovich Kryukov 10,169
1 OriginalGriff 7,749
2 CPallini 4,181
3 Rohan Leuva 3,482
4 Maciej Los 3,089


Advertise | Privacy | Mobile
Web04 | 2.6.130523.1 | Last Updated 14 Dec 2011
Copyright © CodeProject, 1999-2013
All Rights Reserved. Terms of Use
Layout: fixed | fluid