实现简单的malloc管理

实现简单的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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值