头文件(mymem.h):
#ifndef _my_mem_h6314854
#define _my_mem_h6314854
typedef struct humem
{
int flag; //标记是否在使用 // iFlag nFlag
int size; //内存块的大小
humem *pNext; //下一个块的指针
}tMem,*ptMem;
class mymem
{
int num; //内存块数 m_
ptMem pHead; //块区头指针
ptMem createMem(int size); //申请新内存
public:
mymem();
~mymem();
void * getMem(int size); //得到合适的内存
ptMem getHead() { return pHead; }
void freeMem(void * );//释放内存,即设置flag标记为0
};
#endif
实现文件(mymem.cpp):
#include "mymem.h"
#define NULL 0
mymem::mymem()
{
num = 0; //内存块数
pHead = NULL; //块区头指针
}
mymem::~mymem()
{
ptMem temp;
while (pHead!=NULL)
{
temp=pHead;
pHead=pHead->pNext;
delete(temp);
}
}
ptMem mymem::createMem(int size)
{
ptMem temptmem;
temptmem = (tMem *)new char[size + sizeof(tMem)];
if (temptmem == NULL)
{
return NULL;
}
temptmem->flag=0; //未使用内存
temptmem->size=size;
if (pHead==NULL)//第一次申请内存
{
pHead=temptmem;
temptmem->pNext=NULL;
}
else
{
temptmem->pNext=pHead;
pHead=temptmem;
}
return temptmem;
}
void * mymem::getMem(int sizex)
{
ptMem tempm;
tempm=pHead;
while (tempm!=NULL && tempm->flag==0)
{
if (tempm->size>sizex) // 已经找到
{
tempm->flag=1;
return (void *)(tempm + 1);
}
tempm=tempm->pNext;
}
tempm = createMem(sizex);
tempm->flag = 1; // 设置为使用状态
return (void *)(tempm + 1);;
}
void mymem::freeMem(void * pMem)//释放内存,即设置flag标记为0然后将其移动到链表表头
{
ptMem tempm;
tempm = (ptMem)pMem - 1;
ptMem tempmh=pHead;
tempm->flag=0; // 设置为可用状态
if (tempmh!=tempm)
{
while (tempmh->pNext!=tempm)
{
tempmh=tempmh->pNext;
}
tempmh->pNext = tempm->pNext;
tempm->pNext=pHead;
pHead=tempm;
}
}
主程序(main.cpp):
#include <iostream>
using namespace std;
#include "mymem.h"
void main()
{
int i;
mymem humem;
ptMem tempmem;
void * huproA[10];
for (i=0;i<10;i++)
{
huproA[i]=humem.getMem(i*400+4);
}
tempmem=humem.getHead();
while (tempmem!=NULL)
{
cout<<"内存大小:"<<tempmem->size<<"是否在使用"<<tempmem->flag<<endl;
tempmem=tempmem->pNext;
}
humem.freeMem(huproA[0]);
cout<<"_____________________/n";
tempmem=humem.getHead();
while (tempmem!=NULL)
{
cout<<"内存大小:"<<tempmem->size<<"是否在使用"<<tempmem->flag<<endl;
tempmem=tempmem->pNext;
}
}