采用首次适应算法的动态分区分配模拟

本文详细介绍了内存管理过程中的作业回收、分配与调度算法,包括如何根据作业需求分配内存,以及实现内存回收以优化系统资源利用。通过交互式操作界面,用户可以直观地创建作业、查看内存状态并回收内存,提升系统性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <stdio.h>

void hui(Fq *head)
{
	Fq *p=head->next;p->before=head;
	int no=0;
	cout<<"请输入要回收内存的作业号:";cin>>no;
	while(p!=NULL)
	{
		if(p->no==no)
		{
			free(p);
			cout<<"作业"<<no<<"的内存已经回收!"<<endl;
			return ;
		}else{
			p=p->next;
		}
	}
}

void alloc(int b,int no,Fq *p)
{
	while(p!=NULL)
	{
		if(p->o==1){p=p->next;}
		else
		{
			if(p->size>b)
			{
				if(p->size-b<=min_size)
				{
					p->o=1;p->no=no;
				}else{
					Fq *q=new Fq;Fq *r;
					r=q->before;
					r->next=q;q->before=r;
					q->next=p;p->before=q;
					q->size=b;
					p->size=p->size-b;
					q->no=no;
					q->o=1;
				}
			}
			cout<<"内存分配成功!"<<endl;
			return ;
		}else{
			p=p->next;
		}
	}
	cout<<"内存分配失败!"<<endl;
}

void free(Fq *c)
{
	if(c->before->o==0&&c->next->o==0)
	{
		Fq *r=c->before,*s=c->next->next;
		r->size=(r->size+c->size+c->next->size);
		r->next=s;
		if(s!=NULL)s->before=r;
	}
	if(c->before->o==0&&c->next->o!=0)
	{
		c->before->size=c->before->size+c->size;
		c->beofre->next=c->next;c->next->before=c->before;
	}
	if(c->next->o==&&c->before->o!=0)
	{
		Fq *r=c->next->next;
		c->size=c->size+c->next->size;
		c->next=c->next->next;
		if(r!=NULL)r->before=c;
		c->o=0;
	}else{
		c->o=0;
	}
}

void cha(Fq *head)
{
	Fq *p=head->next;p->before=head;
	int i=0;
	cout<<"空闲分区链的情况为:"<<endl;
	while(p!=NULL)
	{
		if(p->o==0)
		{
			cout<<"空闲分区"<<++i<<"  "<p-size<<"K"<<endl;
		}
		p=p->next;
	}
}

void create(Fq *head)
{
	Fq *p=head->next;
	p->before=head;
	int no=0,b=0;
	cout<<"请输入要创建的作业的编号:";cin>>no;
	cout<<"请输入作业的需求空间大小:";cin>>b;
	alloc(b,no,p);
}

int main()
{
	Fq *heand=new Fq;head->next=new Fq;
	head->next->size=MAXSIZE;
	head->next->o=0;
	head->next->next=NULL;
	int choice=0;
	do
	{
		cout<<"请选择你要进行的操作:"<<endl;
		cout<<"1、创建新作业"<<endl;
		cout<<"2、查看空闲分区链"<<endl;
		cout<<"3、回收内存空间"<<endl;
		cout<<"0、退出"<<endl;
		cin>>choice;
		switch(choice)
		{
			case 1:create(head);break;
			case 2:cha(head);break;
			case 3:hui(head);break;
			case 0:break;
			default:cout<<"输入错误!"<<endl;
		}while(choice!=0);
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值