📄 mymemory.cpp
字号:
#include "StdAfx.h"
#include "Block.h"
#include "MyMemory.h"
#include <fstream>
const int MEM_SIZE = 64*1024*1024; //64 M
CMyMemory::CMyMemory(void)
{
pMem = NULL;
/*pMem = new char[MEM_SIZE];
if(!pMem)
{
cerr<<"alloc memory failed.";
}*/
EmptyList.Insert(Block(0,MEM_SIZE),EmptyList.ListSize());
}
CMyMemory::~CMyMemory(void)
{
if(pMem)
delete pMem;
}
//[功能]察看内存的详细使用情况
//[参数]NULL
void CMyMemory::ShowDetail(void)
{
cout<<"Block List:"<<endl;
cout<<"-----------------------------------------------------------------------"<<endl;
for(int i=0;i<EmptyList.ListSize();i++)
{
Block & data = EmptyList.GetData(i);
cout<<"start["<<data.start<<"]\t\tsize["<<data.size<<"]\t\tstate["<<data.flag<<"]\t"<<"No["<<i<<"]"<<endl;
}
cout<<"-----------------------------------------------------------------------"<<endl;
}
//[功能]采用首次适应算法,将分配的内存块插入到空闲分区的前面
//[参数]out[1]成功分配,out[0]分配失败
int CMyMemory::Allocation(int size)
{
int i;
for(i=0;i<EmptyList.ListSize();i++)
{
Block & block = EmptyList.GetData(i);
if(block.size >= size && block.flag == 0)
{
//insert a node to the EmptyList
block.start += size;
block.size -= size;
if(i>=0)
{
Block newBlock(EmptyList.GetData(i-1).size + EmptyList.GetData(i-1).start,size,1);
EmptyList.Insert(newBlock,i);
/*}
else
{
Block newBlock(EmptyList.GetData(-1).size,size,1);
EmptyList.Insert(newBlock,i);*/
}
return 1;
}
}
return 0;
}
//[功能]释放由pos标识的内存快
//[参数]in[pos]为内存块的标号
// out[0]failed
// out[1]sucess
int CMyMemory::Release(int pos)
{
//参数有效性检查,失败返回0
if(pos <0 || pos > EmptyList.ListSize())
{
return 0;
}
//释放内存区,只需要将内存区域标记为未用(flag = 0)即可
if(pos>=0 && pos<EmptyList.ListSize())
{
Block & block = EmptyList.GetData(pos);
block.flag = 0;
}
//若有必要可以在这里调用Merge()合并为用的空暇区块
//Merge();
return 1;
}
//[功能]合并连续未用的内存块为一块
//[参数]NULL
int CMyMemory::Merge(void)
{
int start = 0,size = 0;
int flag = 0,temp = 0;
int i;
for(i=0;i< EmptyList.ListSize();i++)
{
Block & block = EmptyList.GetData(i);
if(! block.flag)
{
//记录连续未用段的开始段的起始地址
if(!flag)
{
start = block.start;
temp = i;
flag = 1;
}
size += block.size;
EmptyList.Delete(i);
i--;
}
else
{
//向链表中插入一块空白的空间大小为连续未用的空间的总和
if(flag)
{
flag = 0;
Block newBlock(start,size,0);
EmptyList.Insert(newBlock,temp);
i = temp;
}
}
}
//合并最后一块连续未用的空间
if(flag)
{
if(size == 0)
{
return 0;
}
Block newBlock(start,size,0);
EmptyList.Insert(newBlock,temp);
}
return 1;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -