Re: Is MFC reusing memory?
Here goes... A bit lengthy, but will let you just copy and paste. I'm
using VC6, BTW.
===============================================
void Test()
{
LPCTSTR szLogFile = _T("C:\\HeapTest_d.log");
LogHeap( szLogFile, _T("At the beginning of the test:") );
{
CStringArray stra;
stra.SetSize(1000000);
for (int n = 0; n < 1000000; ++n)
stra[n] = _T("1234657890123465789012346578901234657890");
LogHeap( szLogFile, _T("After CStringArray is built:") );
}
LogHeap( szLogFile, _T("After CStringArray is destructed:") );
}
===============================================
bool LogHeap(LPCTSTR szFile, LPCTSTR szTitle)
{
CFileException ex;
CFile fLog;
BOOL bRet;
bRet = fLog.Open(szFile, CFile::modeCreate | CFile::modeNoTruncate
| CFile::modeWrite | CFile::shareDenyWrite, &ex);
if ( ! bRet )
return false;
CString strTitle, strReport;
strTitle.Format( _T("%s\r\n========================================
\r\n"), szTitle );
strReport = MakeReport();
fLog.SeekToEnd();
fLog.Write( (LPCTSTR)strTitle, strTitle.GetLength() * sizeof
TCHAR );
fLog.Write( (LPCTSTR)strReport, strReport.GetLength() * sizeof
TCHAR );
return true;
}
===============================================
CString MakeReport()
{
_HEAPINFO hInfo;
int nHeapStatus, nBlockSize;
int nUsed[10], nFree[10], nUsedSize = 0, nFreeSize = 0;
hInfo._pentry = NULL;
ZeroMemory(nUsed, 40);
ZeroMemory(nFree, 40);
while ( ( nHeapStatus = _heapwalk(&hInfo) ) == _HEAPOK )
{
nBlockSize = (int)log10(hInfo._size);
if (hInfo._useflag == _USEDENTRY)
{
++nUsed[nBlockSize];
nUsedSize += hInfo._size;
}
else
{
++nFree[nBlockSize];
nFreeSize += hInfo._size;
}
}
CString strLine, strReport = _T("--- Used heap blocks found ---\r
\n");
int nSize = 1, nTotal = 0;
for (int n = 0; n < 10; ++n)
{
if ( nUsed[n] > 0 )
{
strLine.Format( _T("%ld blocks in size range %ld - %ld0\r
\n"), nUsed[n], nSize, nSize );
strReport += strLine;
nTotal += nUsed[n];
}
nSize *= 10;
}
strLine.Format( _T(">>> %ld bytes used, in %ld blocks.\r\n"),
nUsedSize, nTotal );
strReport += strLine;
nSize = 1;
nTotal = 0;
strReport += _T("--- Free heap blocks found ---\r\n");
for (n = 0; n < 10; ++n)
{
if ( nUsed[n] > 0 )
{
strLine.Format( _T("%ld blocks in size range %ld - %ld0\r
\n"), nFree[n], nSize, nSize );
strReport += strLine;
nTotal += nFree[n];
}
nSize *= 10;
}
strLine.Format( _T(">>> %ld bytes used, in %ld blocks.\r\n"),
nFreeSize, nTotal );
strReport += strLine;
switch (nHeapStatus)
{
case _HEAPEMPTY:
strReport += _T("Heap is empty!\r\n\r\n");
break;
case _HEAPEND:
strReport += _T("Heap checked successfully.\r\n\r\n");
break;
case _HEAPBADPTR:
strReport += _T("ERROR - bad pointer to heap!\r\n\r\n");
break;
case _HEAPBADBEGIN:
strReport += _T("ERROR - bad start of heap!\r\n\r\n");
break;
case _HEAPBADNODE:
strReport += _T("ERROR - bad node in heap!\r\n\r\n");
break;
}
return strReport;
}