操作系统实验教程及linux和windows系统调用编程----张丽芬--清华大学出版社--部分程序源代码--第八章--主存空间的分配与回收--可变分区管理算法
// f.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
/*可变式分区的分配与回收主程序 f.cpp*/
#include "stdio.h"
#define N 5
struct freearea
{int startaddress;
int size;
int state;
}freeblock[N]={{20,20,1},{80,50,1},{150,100,1},{300,30,0},{600,100,1}};
int sumsize=0;
int applyarea;
int sumsize1;
/*定义为作业分配主存空间的函数alloc()*/
int alloc(int applyarea)
{
int i,tag=0;
for(i=0;i<N;i++)
{
sumsize+=freeblock[i].size;
sumsize1+=freeblock[i-1].size;
freeblock[i-1].state=0;
if(freeblock[i].state==1&&sumsize>=applyarea)
{
break;
}
}
freeblock[i].startaddress=freeblock[i].startaddress+(applyarea-sumsize1);
freeblock[i].size=freeblock[i].size-(applyarea-sumsize1);
return 1;
}
////////////////////////////////////////////
void setfree()
{ int s,l,tag1=0,tag2=0,tag3=0,i,j;
printf("input free area startaddress:\n");
scanf("%d",&s);
printf("input free area size:\n");
scanf("%d",&l);
for(i=0;i<N;i++)//////////////////
{
sumsize+=freeblock[i].size;
if(freeblock[i].state==1&&sumsize>=applyarea)
//break;
//}
//{
if(freeblock[i].startaddress==s+l&&freeblock[i].state==1)
{l=l+sumsize;///////////
tag1=1;
for(j=0;j<N;j++)
if(freeblock[j].startaddress+freeblock[j].size==s&&freeblock[j].state==1)
{freeblock[i].state=0;
freeblock[j].size=freeblock[j].size+l;//////
tag2=1;
break;
}
if(tag2==0)
{ freeblock[i].startaddress=s;
freeblock[i].size=l;//////////////////
break;
}
}
}
if(tag1==0)
{ for(i=0;i<N;i++)
if(freeblock[i].startaddress+freeblock[i].size==s&&freeblock[i].state==1)
{ freeblock[i].size=freeblock[i].size+l;///////
tag3=1;
break;
}
if(tag3==0)
for(j=0;j<N;j++)
if(freeblock[j].state==0)
{ freeblock[j].startaddress=s;
freeblock[j].size=l;//////////
freeblock[j].state=1;
break;
}
}
}
//////////////////////////////////////////////////////////
void adjust()
{
int i,j;
struct freearea middata;
for(i=0;i<N;i++)
for(j=0;j<N;j++)
if(freeblock[j].startaddress>freeblock[j+1].startaddress){
middata.startaddress=freeblock[j].startaddress;
middata.size=freeblock[j].size;
middata.state=freeblock[j].state;
freeblock[j].startaddress=freeblock[j+1].startaddress;
freeblock[j].size=freeblock[j+1].size;
freeblock[j].state=freeblock[j+1].state;
freeblock[j+1].startaddress=middata.startaddress;
freeblock[j+1].size=middata.size;
freeblock[j+1].state=middata.state;
}
for(i=0;i<N;i++)
for(j=0;j<N;j++)
if(freeblock[j].state==0 && freeblock[j+1].state==1){
middata.startaddress=freeblock[j].startaddress;
middata.size=freeblock[j].size;
middata.state=freeblock[j].st
ate;
freeblock[j].startaddress=freeblock[j+1].startaddress;
freeblock[j].size=freeblock[j+1].size;
freeblock[j].state=freeblock[j+1].state;