内存溢出检测学习

  最近发现CRT控制台程序没有TRACE和内存溢出检查,很郁闷。无聊中翻看MSDN的Memory Management and the Debug Heap篇,发现C的Debug版本用_malloc_dbg代替malloc,而_malloc_dbg者给数据堆加上一个控制头组成链表,方便记录溢出。原话如下:
  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:
  那个控制头的数据结构如下:
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种内存块,具体含义还没有搞清楚,分别如下
/* 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
  检测内存溢出用_CrtDumpMemoryLeaks(),在crtdbg.h中定义。有时间研究一下crtdbg.h文件。
  参考http://www.cnblogs.com/phinecos/archive/2009/10/29/1592604.html


posted on 2009-11-03 22:53 gewala 阅读(1038) 评论(0)  编辑 收藏 引用 所属分类: C++


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


<2024年4月>
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011

导航

统计

常用链接

留言簿

随笔分类

随笔档案

文章分类

文章档案

设计模式 网络编程

网络

搜索

最新评论

阅读排行榜

评论排行榜