单链表实现内存分配监控

 

main.cpp

#include "oj.h"
#include <string.h>

//存放内存泄漏的地址
void* g_array[1024];

int main(int argc,char* argv[])
{
	memset(g_array,0,sizeof(g_array));

	void* pAddr = MLC_Malloc(4);

	void* pTest[4] = {0};

	pTest[0] = pAddr;

	int nNumber = 0;

	Check_mem(&nNumber,g_array);

	return 0;
}


 

oj.h

//2013/12/4 22:21
//oj上面的题目
//大致意思是这样的,封装内存的分配与释放,分配成功的内存放到链表中
//释放内存调用对应的释放函数。然后检测函数可以检测到是否有内存泄露

#include <stdio.h>

//内存申请的函数
void* MLC_Malloc(int nSizeof);

//内存释放函数
int MLC_Free(void* pAddr);

//检查是否有内存泄漏
void Check_mem(int *pNumber,void ** pArray);

//释放内存泄漏
void Free_leak();

typedef struct node 
{
	void* data;
	node* next;
}Node;

//链表相关操作
void InitNode();

void AddNode(void* pAddress);

void FreeNodeByAddress(void* pAddRess);


 

oj.cpp

#include "oj.h"
#include <malloc.h>

Node startNode;
bool bInitNode = false;

void* MLC_Malloc( int nSize )
{
	if (!bInitNode)
	{
		InitNode();
		bInitNode = true;
	}

	void* pTemp = malloc(sizeof(nSize));
	if ( NULL == pTemp)
	{
		return NULL;
	}

	AddNode(pTemp);

	return pTemp;
}

int MLC_Free( void* pAddr )
{
	FreeNodeByAddress(pAddr);
	return 0;
}

void Check_mem( int *pNumber,void ** pArray )
{
	*pNumber = 0;
	Node* pTemp = startNode.next;
	if ( NULL == pTemp)
	{
		return;
	}

	while( NULL != pTemp)
	{
		pArray[*pNumber] = pTemp->data;
		(*pNumber)++;
		pTemp = pTemp->next;
	}
}

void Free_leak()
{
	if ( NULL == startNode.next)
	{
		return;
	}
	Node* pTemp = startNode.next;
	if ( NULL == pTemp)
	{
		return;
	}

	while( NULL != pTemp)
	{
		Node* p = pTemp->next;

		free(p->data);
		free(p);
		pTemp = p;
	}
}

void InitNode()
{
	startNode.next = NULL;
}

void AddNode( void* pAddress )
{
	Node* pTemp = &startNode;

	while( NULL != pTemp->next)
	{
		pTemp = pTemp->next;
	}

	Node* pNew = (Node*)malloc(sizeof(Node));
	pNew->data = pAddress;
	pNew->next = NULL;

	pTemp->next = pNew;
}

void FreeNodeByAddress( void* pAddRess )
{
	Node* pTemp = &startNode;

	while( NULL != pTemp->next && pTemp->next->data != pAddRess)
	{
		pTemp = pTemp->next;
	}
	
	//p是要释放的节点
	Node* p = pTemp->next;
	pTemp->next = p->next;

	free(p->data);
	free(p);
}


 

你可能感兴趣的:(单链表实现内存分配监控)