-
CMemoryState
After about 16 hours of trying to figure out something I've come to reach a hypothesis...
When using CMemoryState (and its Checkpoint() and Difference()) functions, it effs up when you have a vector contained in it. Check out the following code:
Code:
CMemoryState oldMemState, newMemState, diffMemState;
oldMemState.Checkpoint();
std::vector<TCHAR*> vect;
newMemState.Checkpoint();
_ASSERTE (diffMemState.Difference( oldMemState, newMemState ) == FALSE);
The assertion is thrown in this case.. I was trying for many hours and I'm just ........ed for wasting my time thinking I had a leak in my code... Perhaps I am wrong, but I don't see how I could be with the simple, straight-forward code above.
This is just something to keep in mind if you ever try using CMemoryState to catch a memory leak.
-
vect may free any memory from the heap when it goes out of scope (ie the destructor is called). Try this:
Code:
CMemoryState oldMemState, newMemState, diffMemState;
oldMemState.Checkpoint();
{
std::vector<TCHAR*> vect;
}
newMemState.Checkpoint();
_ASSERTE (diffMemState.Difference( oldMemState, newMemState ) == FALSE);
gg
-
I just ran the code (as you originally posted it) in an MFC dialog app using VC++ 6.0 (and all the patches). I did not get the assert.
Do you have other threads running? CMemoryState is not thread specific since multiple threads can share the same heap.
gg
-
My app has only a single thread.
Believe me, I tried and tried everything you could think of for a day and a half to figure out what was causing the assertion. The reason I was doing so in the first place is because I modified my class to use only dynamically alloc'd c-strings.. Eventually, I made everything static again and was still getting the Difference().
I finally figured that perhaps the vector was causing it since it is the only thing in my class that was allocating any heap. Here are a few things I tried (btw I was doing this from my CMainFrame::OnCreate()):
in my class I have a vect as a private member, so I did this:
Code:
//old checkpoint
Settings *s = new Settings;
delete [] s;
//new checkpoint
or
//old checkpoint
{
Settings s;
}
//new checkpoint
Aside from all that, I just ran it again and didn't get the assertion!!! I really am not crazy, but merely in the Twilight Zone it would seem.. I tested and tested and tested it. I even tested it more after posting this thread and I kept getting the assertion! But I just ran it again and it was fine!
Sometimes I just want to kill myself (not literally, you understand).
Thanks for the response CodePlug... If I ever figure it out it won't be soon enough.