Memory leak detection
-
Can someone provide me with a simple set of code to show heap memory allocation and deallocation? Thank you very much
-
Can someone provide me with a simple set of code to show heap memory allocation and deallocation? Thank you very much
to allocate memory for an object of type OBJECT
OBJECT* obj = new OBJECT;
to allocate memory for an array of objects of type OBJECTOBJECT* obj = new OBJECT[array_size];
to deallocate memory for an object of type OBJECTdelete obj;
to deallocate memory for an array of objects of type OBJECTdelete [] obj;
k_dehairy -
Can someone provide me with a simple set of code to show heap memory allocation and deallocation? Thank you very much
the pink jedi wrote:
Memory leak detection
Here what MSDN say about this :- To detect a memory leak Create a CMemoryState object and call the Checkpoint member function. This creates the first memory snapshot. After your program performs its memory allocation and deallocation operations, create another CMemoryState object and call Checkpoint for that object. This gets a second snapshot of memory usage. Create a third CMemoryState object and call its Difference member function, supplying as arguments the two previous CMemoryState objects. If there is a difference between the two memory states, the Difference function returns a nonzero value. This indicates that some memory blocks have not been deallocated. This example shows what the code looks like: // Declare the variables needed #ifdef _DEBUG CMemoryState oldMemState, newMemState, diffMemState; oldMemState.Checkpoint(); #endif // Do your memory allocations and deallocations. CString s = "This is a frame variable"; // The next object is a heap object. CPerson* p = new CPerson( "Smith", "Alan", "581-0215" ); #ifdef _DEBUG newMemState.Checkpoint(); if( diffMemState.Difference( oldMemState, newMemState ) ) { TRACE( "Memory leaked!\n" ); } #endif Notice that the memory-checking statements are bracketed by #ifdef _DEBUG / #endif blocks so that they are compiled only in Win32 Debug versions of your program.
"Opinions are neither right nor wrong. I cannot change your opinion. I can, however, change what influences your opinion." - David Crow
cheers, Alok Gupta VC Forum Q&A :- I/ IV