C++程序内存泄露检测工具
作者:网络转载 发布时间:[ 2014/10/30 11:20:41 ] 推荐标签:c++ 内测 NET 软件开发
void* _GetBusyNode(void* addr)
{
if ( g_busyList == NULL)
{
return NULL;
}
if ( NULL == g_busyList->next)
{
MemoryInfo* retNode = NULL;
if (g_busyList->data->addr == addr)
{
retNode = g_busyList->data;
delete g_busyList;
g_busyList = NULL;
}
return (void*)retNode;
}
BusyList* pre , *curr;
pre = curr = g_busyList;
while(curr)
{
if (curr->data->addr == addr)
{
BusyList* tmp = curr;
MemoryInfo* retNode = curr->data;
pre->next = curr->next;
free((void*)tmp);
return (void*)retNode;
}
pre = curr;
curr = curr->next;
}
return NULL;
}
void _FreeNode(void* p)
{
if ( NULL == p)
{
return;
}
FreeList* tmpNode = (FreeList*)p;
tmpNode->next = g_freeList;
g_freeList = tmpNode;
}
//保存内存分配信息
void _StoreMemoryAllocInfo(void* addr , size_t size , _UL lineNum , const char* file)
{
MemoryInfo* node = (MemoryInfo*)_GetFreeNode();
if ( NULL == node )
{
return;
}
node->addr =addr;
node->size = size;
node->lineNum = lineNum;
size_t len = strlen(file);
len = len >= MAX_FILE_LEN ? MAX_FILE_LEN - 1 : len;
strncpy(node->fileName , file , len);
node->fileName[len] = '/0';
//增加链表
BusyList* busyNode = (BusyList*)malloc(sizeof(BusyList));
busyNode->data = node;
if ( g_busyList == NULL )
{
g_busyList = busyNode;
busyNode->next = NULL;
}
else
{
busyNode->next = g_busyList;
g_busyList = busyNode;
}
//写入文件
_WriteMemoryInfo(node , true);
}
//保存内存分配信息
void _StoreMemoryDeallocInfo(void* addr)
{
MemoryInfo* node = (MemoryInfo*)_GetBusyNode(addr);
if ( NULL == node )
{
return;
}
//写入文件
_WriteMemoryInfo(node , false);
_FreeNode((void*)node);
}
//写日志函数
void _WriteMemoryInfo(const MemoryInfo* pInfo , bool bAlloc)
{
if (pInfo != NULL)
{
FILE *fp = fopen("debugmemorylog.txt","a+");
if (!fp)
return;
fprintf(fp,"%p:/t%s/t%d line %s %d bytes/n",pInfo->addr, pInfo->fileName, pInfo->lineNum /
, (bAlloc ? "allocated" : "freed") , pInfo->size);
fflush(fp);
fclose(fp);
}
}
//将泄露的内存信息写到磁盘
void DumpLeakedMemoryInfo()
{
FILE *fp = fopen("memoryleak.txt","a+");
if (!fp)
return;
BusyList* p = g_busyList;
while (p)
{
BusyList* tmp = p;
MemoryInfo* pInfo = tmp->data;
if (pInfo != NULL)
{
fprintf(fp,"%p:/t%s/t%d line leak %d bytes/n",pInfo->addr, pInfo->fileName, pInfo->lineNum , pInfo->size);
}
_FreeNode((void*)pInfo);
delete tmp;
tmp = NULL;
p = p->next;
}
fflush(fp);
fclose(fp);
//释放内存池资源给操作系统
_ReleaseFreeList();
}
void _ReleaseFreeList()
{
while(g_freeList)
{
FreeList* tmp = g_freeList->next;
delete g_freeList;
g_freeList = tmp;
}
}
#endif//DETECT_MEMORY_LEAK
本文内容不用于商业目的,如涉及知识产权问题,请权利人联系SPASVO小编(021-61079698-8054),我们将立即处理,马上删除。
相关推荐

更新发布
功能测试和接口测试的区别
2023/3/23 14:23:39如何写好测试用例文档
2023/3/22 16:17:39常用的选择回归测试的方式有哪些?
2022/6/14 16:14:27测试流程中需要重点把关几个过程?
2021/10/18 15:37:44性能测试的七种方法
2021/9/17 15:19:29全链路压测优化思路
2021/9/14 15:42:25性能测试流程浅谈
2021/5/28 17:25:47常见的APP性能测试指标
2021/5/8 17:01:11热门文章
常见的移动App Bug??崩溃的测试用例设计如何用Jmeter做压力测试QC使用说明APP压力测试入门教程移动app测试中的主要问题jenkins+testng+ant+webdriver持续集成测试使用JMeter进行HTTP负载测试Selenium 2.0 WebDriver 使用指南