最近發(fā)現(xiàn)CRT控制臺程序沒有TRACE和內(nèi)存溢出檢查,很郁悶。無聊中翻看MSDN的Memory Management and the Debug Heap篇,發(fā)現(xiàn)C的Debug版本用_malloc_dbg代替malloc,而_malloc_dbg者給數(shù)據(jù)堆加上一個控制頭組成鏈表,方便記錄溢出。原話如下:
When you request a memory block, the debug heap manager allocates from the base
heap a
slightly larger block of memory than requested and returns a pointer to
your portion of that block. For example, suppose your application contains the
call:
malloc( 10 )
. In a release build,
malloc would call the base heap allocation routine
requesting an allocation of 10 bytes. In a debug build, however,
malloc
would call
_malloc_dbg, which would then call
the base heap allocation routine requesting an allocation of 10 bytes plus
approximately 36 bytes of additional memory. All the resulting memory blocks in
the debug heap are connected in a single linked list,
ordered according to when
they were allocated:
那個控制頭的數(shù)據(jù)結構如下:
typedef struct _CrtMemBlockHeader
{
// Pointer to the block allocated just before this one:
struct _CrtMemBlockHeader *pBlockHeaderNext;
// Pointer to the block allocated just after this one:
struct _CrtMemBlockHeader *pBlockHeaderPrev;
char *szFileName; // File name
int nLine; // Line number
size_t nDataSize; // Size of user block
int nBlockUse; // Type of block
long lRequest; // Allocation number
// Buffer just before (lower than) the user's memory:
unsigned char gap[nNoMansLandSize];
} _CrtMemBlockHeader;
這個nBlockUse有6種內(nèi)存塊,具體含義還沒有搞清楚,分別如下
/* Memory block identification */
#define _FREE_BLOCK 0
#define _NORMAL_BLOCK 1
#define _CRT_BLOCK 2
#define _IGNORE_BLOCK 3
#define _CLIENT_BLOCK 4
#define _MAX_BLOCKS 5
檢測內(nèi)存溢出用_CrtDumpMemoryLeaks(),在
crtdbg.h中定義。有時間研究一下crtdbg.h文件。
參考
http://www.cnblogs.com/phinecos/archive/2009/10/29/1592604.html