When a CString object is allocated on the frame, its constructor also allocates memory on the heap to hold the characters of the string. Thus, a CString occupies space on the frame and also on the heap. When a CString frame variable is destroyed normally, its destructor takes care of deallocating the heap space used by the object. When the normal destruction of the CString is bypassed by an exception, this heap space is not deallocated, even though the frame space occupied by the CString is reclaimed.
·To avoid this CString memory leak:
Call the Empty function for any CString frame variables when handling an exception. The following example shows how to do this:
{
CString s1 = "This is a test";
TRY
{
char* p1 = new char[ A_BIG_BLOCK ];
}
CATCH( CMemoryException,e )
{
// deallocate heap space used by string
s1.Empty();
// now you can safely throw the exception
THROW_LAST( );
}
}
The necessity to explicitly deallocate heap resources for a frame-based object is not limited to CStrings. Since the destructors for frame objects are not automatically executed when an exception interrupts normal program flow, any frame-based object where the destructor performs significant tasks will need special attention during exception handling.