实现简单的malloc管理

时间:2021-11-25 03:16:44

实现简单的malloc后未被free的指针地址和大小。

Memory.h

#include <iostream>
#include <map>
using namespace std;
#define MAXN 1024

typedef struct MemeryInfo
{
	size_t msize;
	char filename[MAXN];
	int line;
} MemInfo;

void *MyMalloc(size_t size, char *filename, int line);
void *MyFree(void *ptr);
void MyDump();

#define MALLOC(ptr, size)\
	ptr = (int*)MyMalloc(size, __FILE__, __LINE__);
#define FREE(ptr)\
	MyFree(ptr);
#define DUMP()\
	MyDump();

Memory.cpp

#include "Memery.h"

map<size_t ,MemInfo> Info;
void *MyMalloc(size_t size, char *filename, int line)
{
	if (NULL == filename)
	{
		return NULL;
	}
	void* p = malloc(size);
	if (NULL == p)
	{
		return NULL;
	}
	MemInfo m;
	strcpy(m.filename, filename);
	m.line = line;
	m.msize = size;
	size_t addr = (size_t)p;
	Info.insert(make_pair(addr, m));
	return p;
}

void *MyFree(void *ptr)
{
	size_t addr = (size_t)ptr;
	free(ptr);
	ptr = NULL;
	map<size_t, MemInfo>::iterator it;
	for (it = Info.begin(); it != Info.end(); it++)
	{
		if (it->first == addr)
		{
			Info.erase(it);
			break;
		}
	}
	return NULL;
}

void Print(MemInfo m)
{
	cout << "[Memery Leak] ";
	cout << "in FileName =  [" << m.filename << "], Line = [" << m.line << "], size = [" << m.msize << "] byte(s)." << endl;
}
void MyDump()
{
	if (Info.empty())
	{
		cout << "No Memery Leak !" << endl;
		return;
	}
	map<size_t, MemInfo>::iterator it;
	for (it = Info.begin(); it != Info.end(); it++)
	{
		Print(it->second);
	}
}

main.cpp

#include "Memery.h"

int main()
{
	int *p1, *p2, *p3;
	p1 = MALLOC(p1, 100);
	p2 = MALLOC(p1, 200);
	p3 = MALLOC(p1, 300);
	DUMP();
	FREE(p1);
	DUMP();
	FREE(p2);
	DUMP();
	return 0;
}