Problems with using auto_ptr and _CRTDBG_MAP_ALLOC
Hi All,
What I intend to do and ask for your help is how to use the facility
provided by VC itself to detect and prevent memory leaking.
I have been trying to use auto_ptr and __CRTDBG_MAP_ALLOC to prevent
memory leaks in my application development by doing the following:
1. Include the following in the stdafx.h
#ifdef _DEBUG
// When debugging, turn on the CRT's debugging facilities
// for checking for memory leaks
// (we call _CrtSetDbgFlag in _tWinMain)
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#endif
2. in the main procedure, include the _CrtSetDbgFlag like following:
int _tmain(int argc, _TCHAR* argv[])
{
#ifdef _DEBUG
::_CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
#endif
std::auto_ptr<T> pT = new T;
//T* pT=new T;
//*pShort = 100;
return 0;
}
The program can complile, but when try to run it, I get the following
error:
"Unhandled exception at 0x10252758 (msvcr80d.dll) in testonly.exe:
0xC0000005: Access violation reading location 0xcdcdcdc1."
The program breaks at:
==========
/* verify block type */
_ASSERTE(_BLOCK_TYPE_IS_VALID(pHead->nBlockUse));
==========
in the following function
void operator delete(
void *pUserData
)
{
_CrtMemBlockHeader * pHead;
RTCCALLBACK(_RTC_Free_hook, (pUserData, 0));
if (pUserData == NULL)
return;
_mlock(_HEAP_LOCK); /* block other threads */
__TRY
/* get a pointer to memory block header */
pHead = pHdr(pUserData);
/* verify block type */
_ASSERTE(_BLOCK_TYPE_IS_VALID(pHead->nBlockUse));
_free_dbg( pUserData, pHead->nBlockUse );
__FINALLY
_munlock(_HEAP_LOCK); /* release other threads */
__END_TRY_FINALLY
return;
}
#endif /* _DEBUG */
--
Regards,
peter lin