自我实现内存管理
来源:互联网 发布:aws ubuntu 搭建vpn 编辑:程序博客网 时间:2024/06/05 01:59
在我们使用内存的时候,偶尔会由于疏忽而忘记释放掉已用完的内存,从而引起内存泄露,因此可以写一个内存管理的程序,用来检查那些内存泄露,在什么位置,从而能使程序更高效。
代码如下:
#pragma once //头文件#include <iostream>using namespace std;#include <string>#include <list>#include <assert.h>struct BlockInfo{ void* _ptr; string _file; int _line; BlockInfo(void* ptr, const char* file, int line) :_ptr(ptr) ,_file(file) ,_line(line) {}};void* Alloc(size_t size, const char* file, int line);void Dealloc(void* ptr);void Print();template<class T>T* __NEW(size_t size,const char* file,int line){ T* ptr = (T*)Alloc(size,file,line); return new(ptr) T;}template<class T>void __DELETE(T* ptr){ ptr->~T(); Dealloc(ptr);}#define NEW(type) __NEW<type>(sizeof(type),__FILE__,__LINE__)#define DELETE(ptr) __DELETE(ptr)#define NEW_ARRAY(type,num) __NEW_ARRAY<type>(sizeof(type)*num+4,__FILE__,__LINE__)#define DELETE_ARRAY(ptr) __DELETE_ARRAY(ptr);template<class T>T* __NEW_ARRAY(size_t size,const char* file,int line){ T* ptr = (T*)Alloc(size,file,line); int num = (size-4)/sizeof(T); *((int*)ptr) = num; int i = 0; T* tmp = (T*)(((int*)ptr)+1); while(i < num) { new(tmp) T; ++i; ++tmp; } return (T*)(((int*)ptr)+1);}template<class T>void __DELETE_ARRAY(T* ptr){ int num = *(((int*)ptr)-1); T* tmp = (T*)ptr; while(num) { tmp->~T(); --num; ++tmp; } Dealloc((int*)ptr-1);}
#include "MemoryManager.h" //.cpp文件list<BlockInfo> BlockList;void* Alloc(size_t size, const char* file, int line){ void* ptr = malloc(size); if(ptr != NULL) { BlockInfo info(ptr,file,line); BlockList.push_back(info); } return ptr;}void Dealloc(void* ptr){ free(ptr); if(ptr != NULL) { list<BlockInfo>::iterator it = BlockList.begin(); while(it != BlockList.end()) { if(it->_ptr == ptr) { BlockList.erase(it); return; } ++it; } assert(false); }}void Print(){ cout<<"内存泄露的内存块:"<<endl; list<BlockInfo>::iterator it = BlockList.begin(); while(it != BlockList.end()) { printf("ptr:%p\tfile:%s\tline:%d\n",it->_ptr,it->_file.c_str(),it->_line); ++it; }}
本文出自 “敲完代码好睡觉zzz” 博客,请务必保留此出处http://2627lounuo.blog.51cto.com/10696599/1750625
阅读全文
0 0
- 自我实现内存管理
- 自我学习--内存管理
- C++内存管理自我解惑
- Cache 之自我实现内存缓存
- Nachos内存管理实现
- 内存管理算法实现
- 用单链表实现的内存管理
- 用单链表实现的内存管理
- 用单链表实现的内存管理
- 数据结构内存管理c++实现
- 内存管理的具体实现
- 《敏捷个人-认识自我,管理自我》前言
- 敏捷个人-认识自我,管理自我
- 程序员的自我修养 - 内存
- 《程序员的自我修养》--内存
- java内存机制自我理解
- 管理自我—起始篇
- 自我压力管理的技巧
- 实现将一个字符串转化成对应的整形数字
- 使用mian函数的命令行参数
- 实现一个日期计算器
- 别拿浅拷贝不当拷贝
- Androidstudio 添加so库
- 自我实现内存管理
- 稀疏矩阵的压缩存储及快速转置
- 数据结构——广义表
- Linux平台下变量在栈帧中的存储
- inode及硬链接和软链接
- 进程间通信(IPC)之————管道
- 进程间通信(IPC)之————消息队列
- 进程间通信(IPC)之————信号量
- 进程间通信(IPC)之————共享内存