操作系统存储管理动态分区分配及回收算法附源码

合集下载

操作系统实验动态分区存储管理方式的主存分配回收.

操作系统实验动态分区存储管理方式的主存分配回收.

操作系统实验_动态分区存储管理方式的主存分配回收//////////////////////////////////////////////////////////// // 功能:// 《计算机操作系统》实验// 首次适应性算法// 摸拟动态分区存储管理方式的主存分配和回收// 时间:// 2005-11-14////////////////////////////////////////////////////////////#include "iostream.h"#include "iomanip.h"#define ERR_NOFREEAREA 1#define ERR_NOADEQUACYAREA 2#define ERR_ALLOCATED 4#define ERR_NOJOBS 1#define ERR_NOSUCHJOB 2#define ERR_RECLAIMED 4typedef struct tagUsedNode{long address;long length;int flag; //作业名struct tagUsedNode *next;} USED_AREA , *USED_TABLE;typedef struct tagFreeNode{long address;long length;struct tagFreeNode *next;} FREE_AREA , *FREE_TABLE;//空闲区、作业区链表USED_TABLE usedTable = NULL;FREE_TABLE freeTable = NULL;//给作业分配空间//jobname: 作业名//jobsize: 作业所需空间大小int Allocate( int jobname , long jobsize )//如果没有空闲区if( freeTable == NULL )return ERR_NOFREEAREA;FREE_TABLE p = freeTable;FREE_TABLE q = p;//找首次适应空闲区while( p != NULL && p->length < jobsize ){q = p;p = p->next;}//如果找不到有足够空间的分区if( p == NULL )return ERR_NOADEQUACYAREA;USED_TABLE x = new USED_AREA;x->address = p->address;x->length = jobsize;x->flag = jobname;x->next = NULL;//如果该分区大于作业需求,空间大小减去作业大小if( p->length > jobsize ){p->length -= jobsize;p->address += jobsize;}//如果该分区等于作业大小,删除该分区else{if( p == freeTable )freeTable = NULL;elseq->next = p->next;delete p;}//作业加入“作业表”中USED_TABLE r = usedTable;USED_TABLE t = r;while( r != NULL && r->address < x->address ) {t = r;r = r->next;}if( usedTable == NULL )usedTable = x;else{x->next = r;t->next = x;}return ERR_ALLOCATED;}//回收作业空间//jobname: 作业名int Reclaim( int jobname ){if( usedTable == NULL )return ERR_NOJOBS;USED_TABLE p = usedTable;USED_TABLE q = p;while( p != NULL && p->flag != jobname ){q = p;p = p->next;}//如果没有该作业if( p == NULL )return ERR_NOSUCHJOB;//回收后的空间加入到空闲区FREE_TABLE r = freeTable;FREE_TABLE t = r;FREE_TABLE x;while( r != NULL && r->address < p->address ) {t = r;r = r->next;}x = new FREE_AREA;x->address = p->address;x->length = p->length;x->next = NULL;if( r == freeTable ){x->next = r;freeTable = x;t = freeTable;}else{x->next = r;t->next = x;}//合并分区while( t->next != NULL && t->address + t->length == t->next->address ) {t->length += t->next->length;r = t->next;t->next = t->next->next;delete r;}//删除该作业if( p == usedTable ){usedTable = usedTable->next;}elseq->next = p->next;delete p;return ERR_RECLAIMED;}int Init(){freeTable = new FREE_AREA;freeTable->address = 0;freeTable->length = 1024;freeTable->next = NULL;return 1;}void jobrequest(){int jobname;int jobsize;cout<<"...................."<<endl;cout<<"作业名: ";cin >> jobname;cout<<"作业长度: ";cin >> jobsize;if( Allocate( jobname , jobsize ) == ERR_ALLOCATED )cout<<"该作业已成功获得所需空间"<<endl;elsecout<<"该作业没有获得所需空间"<<endl;cout<<"...................."<<endl;}void jobreclaim(){int jobname;cout<<"...................."<<endl;cout<<"作业名: ";cin >>jobname;int result = Reclaim( jobname );if( result == ERR_RECLAIMED )cout<<"该作业已成功回收"<<endl;else if( result == ERR_NOSUCHJOB || result == ERR_NOJOBS )cout<<"系统没有作业或该作业不存在"<<endl;cout<<"...................."<<endl;}void freeTablePrint(){cout<<"........................................"<<endl;cout<<setw(10)<<"address"<<setw(10)<<"length"<<setw(10)<<"state"<<en dl<<endl;FREE_TABLE p = freeTable;USED_TABLE q = usedTable;int x , y;while( p || q ){if( p )x = p->address;elsex = 0x7fffffff;if( q )y = q->address;elsey = 0x7fffffff;if( x < y ){cout<<setw(10)<<p->address<<setw(10)<<p->length<<setw(10)<<"空闲"<<endl;p = p->next;}if( x > y ){cout<<setw(10)<<q->address<<setw(10)<<q->length<<setw(10)<<"已分配"<<setw(10)<<"ID="<<q->flag<<endl;q = q->next;}}cout<<"........................................"<<endl;}void main(){Init();int choose;bool exitFlag = false;while( !exitFlag ){cout<<"选择功能项( 0 -退出 1 - 分配主存 2 - 回收主存 3 - 显示主存)"<<endl; cout<<"?>";cin>>choose;switch( choose ){case 0:exitFlag = true;break;case 1:jobrequest();break;case 2:jobreclaim();break;case 3:freeTablePrint();break;}}}Trackback: /TrackBack.aspx?PostId=529025。

操作系统-存储管理动态分区分配和恢复算法(带源代码).doc

操作系统-存储管理动态分区分配和恢复算法(带源代码).doc

操作系统-存储管理动态分区分配和恢复算法(带源代码)。

存储管理动态分区分配和恢复算法课程名称:计算机操作系统课程: 信函1501-计算机操作系统类别:信1501:陈丽实验日期:5月XXXX,5月XXXX,5月20日分数: 教师签名:首先,实验目的分区管理是一种广泛使用的存储管理技术。

本实验要求用结构化的高级语言构造分区描述符,编写动态分区分配算法和恢复算法仿真程序,并讨论不同分配算法的特点。

二、实验要求1.写作:首次拟合算法2.写作:最佳拟合算法3.写作:自由区域恢复算法三、实验过程(一)主要程序1.定义分区描述符节点,包括3个元素:(1)adr——分区标题地址(2)大小——分区大小(3)next——指向下一个分区的指针2.定义3个指向节点结构的指针变量:(1)head1——空闲区队列头指针(2)back1——指针指向空闲区节点结构(3)assign——指针指向应用的内存分区节点结构3.定义一个成形变量:免费——用户申请存储区域大小(由用户键入)(2)流程1.定义检查过程以检查指定发布块(由用户键入)的合法性2.定义分配1流程并实施首次拟合算法3.定义分配2过程并实现最佳匹配算法。

4.定义接受1 1流程,并实施首次拟合算法的恢复算法。

5.定义接受2 2过程,实现最佳匹配算法的恢复算法。

6.定义打印过程,打印空闲区队列(3)执行程序首先应用于整个空闲区,第一个地址为0,大小为32767;然后,系统会提示用户使用哪种分配算法,然后是分配还是回收。

分配需要应用程序区域的大小,回收需要释放区域的第一个地址和大小。

CPP # include # include # include # include using命名空间标准;#定义MAX_SIZE 32767typedef结构节点{ int idint adrint大小;结构节点*下一步;}节点;节点*head1,*head2,*back1,*back2,*分配;int请求;内部检查(内部添加、内部大小、字符c){节点*p,*头;int check=1;if(add 0 | | siz next;同时((p!=NULL)检查)如果(((添加:“);sca nf(“% d”,r);if(choosed==' F ' | | choosed==' F ')assign=assign ment 1(num,r);else assign=assignment2(num,r);如果(assign-adr==-1) {printf('未能分配内存!\ n ');Elseprintf('分配成功!分配的内存的第一个地址是:%d\n ',assign-ADR);休息;事例2: printf('输入释放内存的第一个地址:);scanf(“% d”,添加);Printf('输入释放的内存量:);scanf(“% d”,r);Printf('输入释放的内存数量:);scanf(“% d”,rd);if(检查(添加,r,选择)){ if(选择=='f' ||选择=='F') acceptment1(添加,r,rd);else acceptment2(add,r,rd);}休息;case 3:print(已选择);休息;判例4: menu();休息;}}} }}void main()//main函数{ init();菜单();}四.实验结果第五,实验总结通过本实验,我实践了存储管理的动态分区分配和恢复算法,对操作系统中的动态可变分区存储管理有了更深的了解。

实验四动态分区分配算法

实验四动态分区分配算法

实验容:存储器管理实验一、实验目的采用首次适应算法〔FF〕,最正确适应算法〔BF〕,最坏适应算法〔WF〕三种不同的算法,实现对系统空闲区的动态分区分配。

二、实验题目给予顺序搜索的动态分区算法的程序。

三、实验要求读懂给出的核心代码,进展适当的修改,编译通过后,完成实验报告。

四、核心代码#include <stdio.h>#include <stdlib.h>#include <malloc.h>//常量定义#define PROCESS_NAME_LEN 32#define MIN_SLICE 10#define DEFAULT_MEM_SIZE 1024#define DEFAULT_MEM_START 0#define MA_FF 1#define MA_BF 2#define MA_WF 3int mem_size=DEFAULT_MEM_SIZE;int ma_algorithm = MA_FF;static int pid = 0;int flag = 0;struct free_block_type{int size;int start_addr;struct free_block_type *next;};struct free_block_type *free_block;//描述已分配的存块struct allocated_block{int pid; int size;int start_addr;char process_name[PROCESS_NAME_LEN];struct allocated_block *next;};struct allocated_block *allocated_block_head = NULL;//函数声明struct free_block_type* init_free_block(int mem_size);void display_menu();int set_mem_size();void set_algorithm();void rearrange(int algorithm);int rearrange_FF();int rearrange_BF();int rearrange_WF();int new_process();int allocate_mem(struct allocated_block *ab);void kill_process();int free_mem(struct allocated_block *ab);int dispose(struct allocated_block *free_ab);int display_mem_usage();void do_exit();struct allocated_block *find_process(int pid);int main(){char choice; pid=0;free_block= init_free_block(mem_size); //初始化空闲区while(1) {display_menu(); //显示菜单fflush(stdin);choice=getchar(); //获取用户输入switch(choice){case '1': set_mem_size(); break; //设置存大小case '2': set_algorithm();flag=1; break;//设置算法case '3': new_process(); flag=1; break;//创立新进程case '4': kill_process(); flag=1; break;//删除进程case '5': display_mem_usage(); flag=1; break; //显示存使用case '0': do_exit(); exit(0); //释放链表并退出default: break;}}return 1;}struct free_block_type* init_free_block(int mem_size){struct free_block_type *fb;fb=(struct free_block_type *)malloc(sizeof(struct free_block_type));if(fb==NULL){printf("No mem\n");return NULL;}fb->size = mem_size;fb->start_addr = DEFAULT_MEM_START;fb->next = NULL;return fb;}void display_menu(){printf("\n");printf("1 - Set memory size (default=%d)\n", DEFAULT_MEM_SIZE);printf("2 - Select memory allocation algorithm\n");printf("3 - New process \n");printf("4 - T erminate a process \n");printf("5 - Display memory usage \n");printf("0 - Exit\n");}int set_mem_size(){int size;if(flag!=0){ //防止重复设置printf("Cannot set memory size again\n");return 0;}printf("T otal memory size =");scanf("%d", &size);if(size>0) {mem_size = size;free_block->size = mem_size;}flag=1;return 1;}void set_algorithm(){int algorithm;while(1) {printf("\t1 - First Fit\n");printf("\t2 - Best Fit \n");printf("\t3 - Worst Fit \n");scanf("%d", &algorithm);if(algorithm>=1 && algorithm <=3) {ma_algorithm = algorithm;break;}elseprintf("输入有误,请重新输入!\n");}//按指定算法重新排列空闲区链表rearrange(ma_algorithm);}void rearrange(int algorithm){switch(algorithm){case MA_FF: rearrange_FF(); break;case MA_BF: rearrange_BF(); break;case MA_WF: rearrange_WF(); break;}}//首次适应算法int rearrange_FF(){struct free_block_type *temp;//使用头插法,thead为临时头,p为最小地址的数据块的前一个结点struct free_block_type *thead=NULL,*p=NULL;//当前的最小地址int min_addr = free_block->start_addr;temp = free_block;while(temp->next!=NULL) {if(temp->next->start_addr<min_addr) {min_addr = temp->next->start_addr;p = temp;}temp = temp->next;}if(NULL!=p) {temp = p->next;p->next = p->next->next;temp->next = free_block;free_block = temp;}thead = free_block;p = free_block;temp = free_block->next;while(thead->next!=NULL) {min_addr = thead->next->start_addr;while(temp->next!=NULL) {if(temp->next->start_addr<min_addr) {min_addr = temp->next->start_addr;p = temp;}temp = temp->next;}if(p->next!=thead->next) {temp = p->next;p->next = p->next->next;temp->next = thead->next;thead->next = temp;}thead = thead->next;p = thead;temp = thead->next;}return 1;}//最正确适应算法int rearrange_BF(){struct free_block_type *temp;//使用头插法,thead为临时头,p为最小存的数据块的前一个结点struct free_block_type *thead=NULL,*p=NULL;//当前的最小存int min_size = free_block->size;temp = free_block;while(temp->next!=NULL) {if(temp->next->size<min_size) {min_size = temp->next->size;p = temp;}temp = temp->next;}if(NULL!=p) {temp = p->next;p->next = p->next->next;temp->next = free_block;free_block = temp;}thead = free_block;p = free_block;temp = free_block->next;while(thead->next!=NULL) {min_size = thead->next->size;while(temp->next!=NULL) {if(temp->next->size<min_size) {min_size = temp->next->size;p = temp;}temp = temp->next;}if(p->next!=thead->next) {temp = p->next;p->next = p->next->next;temp->next = thead->next;thead->next = temp;}thead = thead->next;p = thead;temp = thead->next;}return 1;}//最坏适应算法int rearrange_WF(){struct free_block_type *temp;//使用头插法,thead为临时头,p为最大存的数据块的前一个结点struct free_block_type *thead=NULL,*p=NULL;//当前的最大存int max_size = free_block->size;temp = free_block;while(temp->next!=NULL) {if(temp->next->size>max_size) {max_size = temp->next->size;p = temp;}temp = temp->next;}if(NULL!=p) {temp = p->next;p->next = p->next->next;temp->next = free_block;free_block = temp;}thead = free_block;p = free_block;temp = free_block->next;while(thead->next!=NULL) {max_size = thead->next->size;while(temp->next!=NULL) {if(temp->next->size>max_size) {max_size = temp->next->size;p = temp;}temp = temp->next;}if(p->next!=thead->next) {temp = p->next;p->next = p->next->next;temp->next = thead->next;thead->next = temp;}thead = thead->next;p = thead;temp = thead->next;}return 1;}int new_process(){struct allocated_block *ab;int size;int ret;ab = (struct allocated_block *)malloc(sizeof(struct allocated_block));if(!ab) exit(-5);ab->next = NULL;pid++;sprintf(ab->process_name, "PROCESS-d", pid);ab->pid = pid;while(1) {printf("Memory for %s:", ab->process_name);scanf("%d", &size);if(size>0) {ab->size=size;break;}else printf("输入大小有误,请重新输入\n");}ret = allocate_mem(ab);if((ret==1) &&(allocated_block_head == NULL)){allocated_block_head=ab;return 1;}else if (ret==1) {ab->next = allocated_block_head;allocated_block_head = ab;return 2; }else if(ret==-1){printf("Allocation fail\n");pid--;free(ab);return -1;}return 3;}int allocate_mem(struct allocated_block *ab){struct free_block_type *fbt, *pre,*head,*temp,*tt;struct allocated_block *tp;int request_size=ab->size;int sum=0;int max;head = (struct free_block_type *)malloc(sizeof(struct free_block_type));pre = head;fbt = free_block;pre->next = fbt;if(ma_algorithm==MA_WF) {if(NULL==fbt||fbt->size<request_size)return -1;}else {while(NULL!=fbt&&fbt->size<request_size) {pre = fbt;fbt = fbt->next;}}if(NULL==fbt||fbt->size<request_size) {if(NULL!=free_block->next) {sum = free_block->size;temp = free_block->next;while(NULL!=temp) {sum += temp->size;if(sum>=request_size)break;temp = temp->next;}if(NULL==temp)return -1;else {pre = free_block;max = free_block->start_addr;fbt = free_block;while(temp->next!=pre) {if(max<pre->start_addr) {max = pre->start_addr;fbt = pre;}pre = pre->next;}pre = free_block;while(temp->next!=pre) {tp = allocated_block_head;tt = free_block;if(pre!=fbt) {while(NULL!=tp) {if(tp->start_addr>pre->start_addr)tp->start_addr = tp->start_addr - pre->size;tp = tp->next;}while(NULL!=tt) {if(tt->start_addr>pre->start_addr)tt->start_addr = tt->start_addr - pre->size;tt = tt->next;}}pre = pre->next;}pre = free_block;while(pre!=temp->next) {if(pre!=fbt)free(pre);pre = pre->next;}free_block = fbt;free_block->size = sum;free_block->next = temp->next;if(free_block->size - request_size < MIN_SLICE) {ab->size = free_block->size;ab->start_addr = free_block->start_addr;pre = free_block;free_block = free_block->next;free(pre);}else {ab->start_addr = fbt->start_addr;free_block->start_addr = free_block->start_addr + request_size;free_block->size = free_block->size - request_size;}}}elsereturn -1;}else {//将存块全局部配if(fbt->size - request_size < MIN_SLICE) {ab->size = fbt->size;ab->start_addr = fbt->start_addr;if(pre->next==free_block) {free_block = fbt->next;}elsepre->next = fbt->next;free(fbt);}else {ab->start_addr = fbt->start_addr;fbt->start_addr = fbt->start_addr + request_size;fbt->size = fbt->size - request_size;}}free(head);rearrange(ma_algorithm);return 1;}void kill_process(){struct allocated_block *ab;int pid;printf("Kill Process, pid=");scanf("%d", &pid);ab = find_process(pid);if(ab!=NULL){free_mem(ab);dispose(ab);}else {printf("没有pid为%d的进程!\n",pid);}}struct allocated_block *find_process(int pid) {struct allocated_block *ab=NULL;ab = allocated_block_head;while(NULL!=ab&&ab->pid!=pid)ab = ab->next;return ab;}int free_mem(struct allocated_block *ab){int algorithm = ma_algorithm;struct free_block_type *fbt, *pre=NULL,*head;fbt=(struct free_block_type*) malloc(sizeof(struct free_block_type));pre=(struct free_block_type*) malloc(sizeof(struct free_block_type));if(!fbt) return -1;// 进展可能的合并,根本策略如下// 1. 将新释放的结点插入到空闲分区队列末尾// 2. 对空闲链表按照地址有序排列// 3. 检查并合并相邻的空闲分区// 4. 将空闲链表重新按照当前算法排序head = pre;fbt->start_addr = ab->start_addr;fbt->size = ab->size;fbt->next = free_block; //新释放的结点插入到空闲分区链表的表头free_block = fbt;rearrange_FF(); //对空闲链表按照地址有序排列pre->next = free_block; //求的pre为fbt的前一个结点pre->size = 0;while(pre->next->start_addr!=fbt->start_addr)pre = pre->next;//左右分区都存在if(0!=pre->size&&NULL!=fbt->next) {//左右分区都可合并if((pre->start_addr+pre->size)==fbt->start_addr && (fbt->start_addr+fbt->size)==fbt->next->start_addr) {pre->size = pre->size + fbt->size + fbt->next->size;pre->next = fbt->next->next;free(fbt->next);free(fbt);}//左分区可合并else if((pre->start_addr+pre->size)==fbt->start_addr) {pre->size = pre->size + fbt->size;pre->next = fbt->next;free(fbt);}//右分区可合并else if((fbt->start_addr+fbt->size)==fbt->next->start_addr) {fbt->size = fbt->size + fbt->next->size;fbt->next = fbt->next->next;free(fbt->next);}}//左分区不存在else if(0==pre->size) {if((fbt->start_addr+fbt->size)==fbt->next->start_addr) {fbt->size = fbt->size + fbt->next->size;fbt->next = fbt->next->next;free(fbt->next);}}//右分区不存在else if(NULL==fbt->next) {if((pre->start_addr+pre->size)==fbt->start_addr) {pre->size = pre->size + fbt->size;pre->next = fbt->next;free(fbt);}}rearrange(algorithm);free(head);return 1;}int dispose(struct allocated_block *free_ab){struct allocated_block *pre, *ab;if(free_ab == allocated_block_head) {allocated_block_head = allocated_block_head->next;free(free_ab);return 1;}pre = allocated_block_head;ab = allocated_block_head->next;while(ab!=free_ab){ pre = ab; ab = ab->next; }pre->next = ab->next;free(ab);return 2;}int display_mem_usage(){struct free_block_type *fbt=free_block;struct allocated_block *ab=allocated_block_head;if(fbt==NULL) return(-1);printf("----------------------------------------------------------\n");printf("Free Memory:\n");printf(" s s\n", " start_addr", " size");while(fbt!=NULL){printf(" d d\n", fbt->start_addr, fbt->size);fbt=fbt->next;}printf("\nUsed Memory:\n");printf("s s s s\n", "PID", "ProcessName", "start_addr", " size");while(ab!=NULL){printf("d s d d\n", ab->pid, ab->process_name, ab->start_addr, ab->size);ab=ab->next;}printf("----------------------------------------------------------\n");return 0;}void do_exit() {}。

操作系统内存的分配与回收

操作系统内存的分配与回收
struct
{
float address; /*空闲区起始地址*/
float length; /*空闲区长度,单位为字节*/
int flag; /*空闲区表登记栏标记,用0表示空栏目,用1表示未分配*/
}free_table[m];/*空闲区表*/
struct{
float address;/*已分分区起始地址*/
{
if(used_table[i].flag!=0)
{
printf("%d\t\t",i);
printf("%f\t\t",used_table[i].address);
printf("%f\t\t",used_table[i].length);
printf("%d\t\t\n",used_table[i].flag);;
used_table[t].length=0;
used_table[t].flag=0;
used_table[t].address=0;
}
}
初始状态:
分配三个主存:
分配一个大小为253:
分配一个大小为90:
分配一个大小为30:
此时的状态为:
回收:
回收90:
#define minisize 100 /*空闲区_申请空间≤minisize时,分配整个空闲区*/
#define n 4/*假定系统允许的最大作业为n,假定模拟实验中n值为10*/
#define m 4 /*假定系统允许的空闲区表最大为m*/
#include <stdio.h>
/*系统中主要数据结构*/
break;
case 3:

操作系统-存储管理动态分区分配及回收算法(附源码)

操作系统-存储管理动态分区分配及回收算法(附源码)

存储管理动态分区分配及回收算法课程名称:计算机操作系统班级:信1501-2实验者姓名:李琛实验日期:2018年5月20日评分:教师签名:一、实验目的分区管理是应用较广泛的一种存储管理技术。

本实验要求用一种结构化高级语言构造分区描述器,编制动态分区分配算法和回收算法模拟程序,并讨论不同分配算法的特点.二、实验要求1、编写:First Fit Algorithm2、编写:Best Fit Algorithm3、编写:空闲区回收算法三、实验过程(一)主程序1、定义分区描述器node,包括3 个元素:(1)adr——分区首地址(2)size-—分区大小(3)next——指向下一个分区的指针2、定义3 个指向node 结构的指针变量:(1)head1—-空闲区队列首指针(2)back1-—指向释放区node 结构的指针(3)assign——指向申请的内存分区node 结构的指针3、定义1 个整形变量:free——用户申请存储区的大小(由用户键入)(二)过程1、定义check 过程,用于检查指定的释放块(由用户键入)的合法性2、定义assignment1 过程,实现First Fit Algorithm3、定义assignment2 过程,实现Best Fit Algorithm4、定义acceptment1 过程,实现First Fit Algorithm 的回收算法5、定义acceptment2 过程,实现Best Fit Algorithm 的回收算法6、定义print 过程,打印空闲区队列(三)执行程序首先申请一整块空闲区,其首址为0,大小为32767;然后,提示用户使用哪种分配算法,再提示是分配还是回收;分配时要求输入申请区的大小,回收时要求输入释放区的首址和大小。

实验代码Main。

cpp#include〈stdio。

h〉#include<stdlib。

h〉#include<string。

操作系统实验——磁盘存储空间的分配和回收C++源程序

操作系统实验——磁盘存储空间的分配和回收C++源程序

#include<stdio.h>#include<stdlib.h>#define NUM 128typedef struct{ int zm_no;int cd_no;int jl_no;}disk;void disp(int m[]){int i;printf("位?示º?图ª?:êo\n");for(i=0;i<NUM;i++){if(i%8==0)printf("\n");printf("%d\t",m[i]);}printf("\n");}void creat(int m[]){ int j=0,zh,wh;int keyong=0;while(j<NUM){ if(m[j]==0){ keyong=1;m[j]=1;disk a;a.zm_no=j/8;a.cd_no=(j%8)/4;a.jl_no=(j%8)%4;zh=a.zm_no;wh=a.cd_no*4+a.jl_no;printf("柱¨´面?号?\t磁ä?道̨¤号?\t物?理¤¨ª记?录?号?\n");printf("%d\t%d\t%d\n",a.zm_no,a.cd_no,a.jl_no);printf("字Á?号?\t位?号?\n");printf("%d\t%d\n",zh,wh);break;}else j++;}if(keyong==0){ printf("无T可¨¦用®?磁ä?盘¨¬块¨¦!ê?\n");printf("\n");}}void del(int m[]){ disk b;int zm_no,cd_no,jl_no,j;printf("输º?入¨?待äy回?收º?磁ä?盘¨¬块¨¦的Ì?柱¨´面?号?,ê?磁ä?道̨¤号?,ê?物?理¤¨ª记?录?号?:êo");scanf("%d%d%d",&b.zm_no,&b.cd_no,&b.jl_no);j=8*b.zm_no+4*b.cd_no+b.jl_no;if(m[j]==0)printf("已°?是º?空?闲D状Á¡ä态¬?,ê?不?必À?回?收º?!ê?\n");else{ m[j]=0;disp(m);}}int main(){int i;int input=1;int m[NUM]={ 0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1};while(input!=0){ printf("1.当Ì¡À前¡ã磁ä?盘¨¬状Á¡ä态¬? 2.申¦¨º请?磁ä?盘¨¬块¨¦ 3.回?收º?磁ä?盘¨¬块¨¦ 0.退ª?出?\n");scanf("%d",&input);switch(input){ case 1: disp(m);break;case 2: creat(m);break;case 3: del(m);break;default:break;}}system("pause");return 0;}。

操作系统实验3-动态分区存储管理

操作系统实验3-动态分区存储管理

实验三动态分区存储管理一:实验目的了解动态分区存储管理方式中的数据结构和分配算法,加深对动态分区存储管理方式及其实现技术的理解。

二:实验内容用C语言或Pascal语言分别实现采用首次适应算法和最佳适应算法的动态分区分配过程Allocate()和回收过程Free()。

其中,空闲分区采用空闲分区链来组织,内存分配时,优先使用空闲区低地址部分的空间。

三:实验类别动态分区存储管理四:实验类型模拟实验五:主要仪器计算机六:结果和小结七:程序#include<stdio.h>#include<time.h>#include<stdlib.h>#define SIZE 640 // 内存初始大小#define MINSIZE 5 // 碎片最小值struct memory{struct memory *former;//前向指针int address;//地址int num;//作业号int size;//分配内存大小int state;//状态0表示空闲,1表示已分配struct memory *next;//后向指针}linklist;void intmemory()// 初始化空闲分区链{memory *p=(memory *)malloc(sizeof(memory));// 分配初始分区内存p->address=0;// 给首个分区赋值p->size=SIZE;p->state=0;p->num=-1;p->former=&linklist;p->next=NULL;linklist.former=NULL;// 初始化分区头部信息linklist.next=p;}int firstFit(int num, int size)// 首次适应算法{memory *p = linklist.next;while(p != NULL){if(p->state == 0 && p->size >= size) // 找到要分配的空闲分区{if(p->size - size <= MINSIZE)// 整块分配{p->state = 1;p->num = num;}else // 分配大小为size的区间{memory *node=(memory *)malloc(sizeof(memory));node->address=p->address + size;node->size=p->size-size;node->state=0;node->num=-1;// 修改分区链节点指针node->former=p;node->next=p->next;if(p->next !=NULL){p->next->former=node;}p->next = node;// 分配空闲区间p->size = size;p->state = 1;p->num = num;}printf("内存分配成功!\n");return 1;}p = p->next;}printf("找不到合适的内存分区,分配失败...\n");return 0;}int bestFit(int num, int size)// 最佳适应算法{memory *tar=NULL;int tarSize=SIZE + 1;memory *p=linklist.next;while(p!=NULL){if(p->state==0 && p->size >= size && p->size < tarSize) //寻找最佳空闲区间{tar=p;tarSize=p->size;}p=p->next;}if(tar!=NULL){if(tar->size - size <= MINSIZE) //找到要分配的空闲分区{tar->state = 1;// 整块分配tar->num=num;}else // 分配大小为size的区间{memory *node = (memory *)malloc(sizeof(memory));node->address = tar->address + size;node->size = tar->size - size;node->state = 0;node->num = -1;// 修改分区链节点指针node->former = tar;node->next = tar->next;if(tar->next != NULL){tar->next->former = node;}tar->next = node;// 分配空闲区间tar->size = size;tar->state = 1;tar->num = num;}printf("内存分配成功!\n");return 1;} else{// 找不到合适的空闲分区printf("找不到合适的内存分区,分配失败!!\n");return 0;}}int freememory(int num)// 回收内存{int flag=0;memory *p=linklist.next, *pp;while(p!=NULL){if(p->state==1 && p->num==num){flag = 1;if((p->former!= &linklist && p->former->state == 0) && (p->next != NULL && p->next->state == 0)){// 情况1:合并上下两个分区// 先合并上区间pp=p;p=p->former;p->size+=pp->size;p->next=pp->next;pp->next->former=p;free(pp);// 后合并下区间pp=p->next;p->size+=pp->size;p->next=pp->next;if(pp->next!=NULL){pp->next->former=p;}free(pp);}else if((p->former==&linklist || p->former->state==1)&& (p->next!=NULL&&p->next->state ==0)) {// 情况2:只合并下面的分区pp=p->next;p->size+=pp->size;p->state=0;p->num=-1;p->next=pp->next;if(pp->next!= NULL){pp->next->former=p;}free(pp);}else if((p->former!=&linklist&&p->former->state==0)&& (p->next==NULL || p->next->state==1)) {// 情况3:只合并上面的分区pp=p;p=p->former;p->size+=pp->size;p->next=pp->next;if(pp->next != NULL) {pp->next->former = p;}free(pp);}else{// 情况4:上下分区均不用合并p->state=0;p->num=-1;}}p=p->next;}if(flag==1){// 回收成功printf("内存分区回收成功...\n");return 1;}else{// 找不到目标作业,回收失败printf("找不到目标作业,内存分区回收失败...\n");return 0;}}// 显示空闲分区链情况void showmemory(){printf(" 当前的内存分配情况如下:\n");printf("*********************************************\n");printf(" 起始地址| 空间大小| 工作状态| 作业号\n");memory *p=linklist.next;while(p!=NULL){printf("******************************************\n");printf("**");printf("%5d k |", p->address);printf("%5d k |", p->size);printf(" %5s |", p->state == 0 ? "0" : "1");if(p->num > 0) {printf("%5d ", p->num);} else {printf(" ");}p = p->next;}}int main(){int option, ope, num, size;// 初始化空闲分区链intmemory();// 选择分配算法l1: while(1){printf("***************************************\n");printf("请选择要模拟的分配算法:\n1表示首次适应算法\n2表示最佳适应算法\n");printf("***************************************\n");scanf("%d", &option);system("cls");if(option==1) {printf("你选择了首次适应算法,下面进行算法的模拟\n");break;} else if(option==2) {printf("你选择了最佳适应算法,下面进行算法的模拟\n");break;}else {printf("错误:请输入0/1\n\n");}}// 模拟动态分区分配算法while(1){printf("\n");printf("*********************************************\n");printf("1:分配内存\n 2:回收内存\n 3:返回上一级菜单\n\n");printf("*********************************************\n");scanf("%d", &ope);system("cls");if(ope==0) break;if(ope==1){// 模拟分配内存printf("请输入作业号:");scanf("%d", &num);printf("请输入需要分配的内存大小(KB):");scanf("%d", &size);if(size<=0){printf("错误:分配内存大小必须为正值\n");continue;}// 调用分配算法if(option==0){firstFit(num, size);}else{bestFit(num, size);}// 显示空闲分区链情况showmemory();}else if(ope==2){// 模拟回收内存printf("请输入要回收的作业号:");scanf("%d", &num);freememory(num);// 显示空闲分区链情况showmemory();}else if(ope==3){goto l1;}else{printf("错误:请输入0/1/2\n");}}printf("分配算法模拟结束\n");return 0;}。

操作系统实验二存储管理动态分区分配及回收算法

操作系统实验二存储管理动态分区分配及回收算法

实验二存储管理动态分区分配及回收算法一、实验目的通过分区管理实验,了解操作系统的基本概念,理解计算机系统的资源如何组织,操作系统如何有效地管理这些系统资源,用户如何通过操作系统与计算机系统打交道。

通过课程设计,我们可以进一步理解在计算机系统上运行的其它各类操作系统,并懂得在操作系统的支持下建立自己的应用系统。

二、实验要求本实验要求用一种结构化高级语言构造分区描述器,编制动态分区分配算法和回收算法模拟程序,并掌握分配算法的特点,提高编程技巧和对算法的理解和掌握。

三、实验过程1.准备(一)主程序1、定义分区描述器node,包括 3个元素:(1)adr——分区首地址(2)size——分区大小(3)next——指向下一个分区的指针2、定义 3个指向node结构的指针变量:(1)head1——空闲区队列首指针(2)back1——指向释放区node结构的指针(3)assign——指向申请的内存分区node结构的指针3、定义 1个整形变量:free——用户申请存储区的大小(由用户键入)(二)过程1、定义check过程,用于检查指定的释放块(由用户键入)的合法性2、定义assignment1过程,实现First Fit Algorithm3、定义assignment2过程,实现Best Fit Algorithm4、定义acceptment1过程,实现First Fit Algorithm的回收算法5、定义acceptment2过程,实现Best Fit Algorithm的回收算法6、定义print过程,打印空闲区队列(三)执行程序首先申请一整块空闲区,其首址为0,大小为32767;然后,提示用户使用哪种分配算法,再提示是分配还是回收;分配时要求输入申请区的大小,回收时要求输入释放区的首址和大小。

(四)输出要求每执行一次,输出一次空闲区队列情况,内容包括:编号首址终址大小2.主要流程和源代码实验二源代码#include<stdio.h>#include<stdlib.h>#include<string.h>#define MAX_SIZE 32767typedef struct node {int id;int adr;int size;struct node *next;}Node;Node *head1,*head2,*back1,*back2,*assign;int request;int check(int add,int siz,char c){Node *p,*head;int check=1;if(add<0||siz<0)check=0;/*地址和大小不能为负*/if(c=='f'||c=='F')head=head1;elsehead=head2;p=head->next;while((p!=NULL)&&check)if(((add<p->adr)&&(add+siz>p->adr))||((add>=p->adr)&&(add<p->adr+p->size))) check=0;elsep=p->next;if(check==0)printf("\t输入释放区地址或大小有错误!!!\n");return check;}void init(){Node *p;head1=(Node*)malloc(sizeof(Node));head2=(Node*)malloc(sizeof(Node));p=(Node*)malloc(sizeof(Node));head1->next=p;head2->next=p;p->size=MAX_SIZE;p->adr=0;p->next=NULL;p->id=0;}Node* assignment1(int num,int req){Node *before,*after,*ass;ass=(Node*)malloc(sizeof(Node));before=head1;after=head1->next;ass->id=num;ass->size=req;while(after->size<req){before=before->next;after=after->next;}if(after==NULL){ass->adr=-1; }else{if(after->size==req){before->next=after->next;ass->adr=after->adr;}else{after->size-=req;ass->adr=after->adr;after->adr+=req;}}return ass;}void acceptment1(int address,int siz,int rd){Node *before,*after;int insert=0;back1=(Node*)malloc(sizeof(Node));before=head1;after=head1->next;back1->adr=address;back1->size=siz;back1->id=rd;back1->next=NULL;while(!insert&&after){//将要被回收的分区插入空闲区(按首址大小从小到大插入)if((after==NULL)||((back1->adr<=after->adr)&&(back1->adr>=before->adr))) {before->next=back1;back1->next=after;insert=1;}else{before=before->next;after=after->next;}}if(insert){if(back1->adr==before->adr+before->size){//和前边分区合并before->size+=back1->size;before->next=back1->next;free(back1);}else if(after&&back1->adr+back1->size==after->adr){//和后边分区合并back1->size+=after->size;back1->next=after->next;back1->id=after->id;free(after);after=back1;}printf("\t首先分配算法回收内存成功!\n");}elseprintf("\t首先分配算法回收内存失败!\n");}Node* assignment2(int num,int req){Node *before,*after,*ass,*q;ass=(Node*)malloc(sizeof(Node));q=(Node*)malloc(sizeof(Node));before=head2;after=head2->next;ass->id=num;ass->size=req;while(after->size<req){before=before->next;after=after->next;}if(after==NULL){ass->adr=-1;}else{if(after->size==req){before->next=after->next;ass->adr=after->adr;}else{q=after;before->next=after->next;ass->adr=q->adr;q->size-=req;q->adr+=req;before=head2;after=head2->next;if(after==NULL){before->next=q;q->next=NULL;}else{while((after->size)<(q->size)){before=before->next;after=after->next;}before->next=q;q->next=after;}}}return (ass);}void acceptment2(int address,int siz,int rd) {Node *before,*after;int insert=0;back2=(Node*)malloc(sizeof(Node)); before=head2;after=head2->next;back2->adr=address;back2->size=siz;back2->id=rd;back2->next=NULL;if(head2->next==NULL){//空闲队列为空head2->next=back2;head2->size=back2->size;}else{//空闲队列不为空while(after){if(back2->adr==after->adr+after->size) {//和前边空闲分区合并before->next=after->next;after->size+=back2->size;back2=after;}else{before=before->next;after=after->next;}}before=head2;after=head2->next;while(after){if(after->adr==back2->adr+back2->size) {//和后边空闲区合并before->next=after->next;back2->size+=after->size;}else{before=before->next;after=after->next;}}before=head2;after=head2->next;while(!insert){//将被回收的块插入到恰当的位置(按分区大小从小到大)if(after==NULL||((after->size>back2->size)&&(before->size<back2->size))) {before->next=back2;back2->next=after;insert=1;break;}else{before=before->next;after=after->next;}}}if(insert)printf("\t最佳适应算法回收内存成功!\n");elseprintf("\t最佳适应算法回收内存失败!!\n");}void print(char choice)//输出空闲区队列信息{Node *p;if(choice=='f'||choice=='F')p=head1->next;elsep=head2->next;if(p){printf("\n空闲区队列的情况为:\n");printf("\t编号\t首址\t终址\t大小\n");while(p){printf("\t%d\t%d\t%d\t%d\n",p->id,p->adr,p->adr+p->size-1,p->size);p=p->next;}}}void menu()//菜单及主要过程{char chose;int ch,num,r,add,rd;while(1){system("cls");printf("选择最先适应算法请输入F,选择最佳适应算法请输入B,退出程序请输入E\n\n"); printf("请输入你的选择:");scanf("%c",&chose);if(chose=='e'||chose=='E')exit(0);else{system("cls");while(1){if(chose=='f'||chose=='F')printf("最先适应算法(First-Fit)模拟:\n");if(chose=='b'||chose=='B')printf("最佳适应算法(Best-Fit)模拟:\n");printf("1.分配内存,2.回收内存,3.查看内存,4.返回\n\n");printf("请输入你的选择:");scanf("%d",&ch);fflush(stdin);switch(ch){case 1:printf("输入申请的分区大小:");scanf("%d",&r);if(chose=='f'||chose=='F')assign=assignment1(num,r);elseassign=assignment2(num,r);if(assign->adr==-1){printf("分配内存失败!\n");}elseprintf("分配成功!分配的内存的首址为:%d\n",assign->adr);break;case 2:printf("输入释放的内存的首址:");scanf("%d",&add);printf("输入释放的内存的大小:");scanf("%d",&r);printf("输入释放的内存的编号:");scanf("%d",&rd);if(check(add,r,chose)) {if(chose=='f'||chose=='F') acceptment1(add,r,rd); elseacceptment2(add,r,rd);}break;case 3:print(chose);break;case 4:menu();break;}}}}}void main()//主函数{init();menu();}四、实验结果五、实验总结通过这次课程设计我练习了用C语言写系统软件,对操作系统中可变分区存储管理有了更深刻的了解。

动态分区分配算法c语言代码

动态分区分配算法c语言代码

动态分区分配算法c语言代码动态分区分配算法是操作系统管理内存时不可或缺的一部分。

它能够动态地将物理内存划分成多个分区,并向进程提供所需的内存空间。

因此,使用动态分区分配算法,可以提高操作系统的内存利用率,优化内存管理。

动态分区分配算法的实现非常复杂,但是通过c语言,可以精确地描述出这一算法。

一般而言,动态分区分配算法需要考虑以下几个方面:1. 内部碎片问题:由于分配内存时分配的大小和分区大小并不总是完全匹配,会产生未使用的部分。

动态分区分配算法需要减少这种情况的发生。

2. 外部碎片问题:在进程运行结束后,会留下未使用的内存。

这些未使用的内存小于内存分区大小,被称为外部碎片。

动态分区分配算法需要将这些未使用的小块内存合并起来,以供分配。

在c语言中,动态分区分配算法的实现方式可以借助链表的数据结构,来实现对内存空间的分配与释放。

一个内存分区对应的链表节点,包含了分区的起始地址,分区的大小以及该分区的状态(是否被分配或是否为空)等信息。

下面是一个简单的动态分区分配算法的示例代码。

在这个代码中,初始化时,将整个可用内存视为一个空闲分区,并创建分配内存时使用的节点。

分配内存时,会遍历空闲分区链表,找到第一个大小足够的分区并将其分配。

释放内存时,遍历已分配分区链表,找到需要释放的分区,并将其状态更改为未分配,并将其添加到空闲分区链表中。

```include <stdio.h>include <stdlib.h>include <stdbool.h>// 内存分区结构体typedef struct partition {int size; // 分区大小bool allocated; // 是否被分配struct partition* next; // 下一个分区节点} partition_t;// 全局链表头节点指针partition_t* head;// 初始化函数void initialize(int size) {head = (partition_t*)malloc(sizeof(partition_t));head->size = size;head->allocated = false;head->next = NULL;}// 分配函数void* allocate(int size) {partition_t* current = head;while (current != NULL) {if (current->size >= size && !current->allocated) {if (current->size == size) {current->allocated = true;} else {partition_t* new_part =(partition_t*)malloc(sizeof(partition_t));new_part->size = size;new_part->allocated = true;new_part->next = current->next;current->size -= size;current->next = new_part; }return (void*)(current + 1); }current = current->next;}printf("Memory allocation failed\n"); return NULL;}// 释放函数void free_memory(void* ptr) {partition_t* current = head;partition_t* prev = head;while (current != NULL) {if ((void*)(current + 1) == ptr) { current->allocated = false;// 尝试合并空闲分区节点if (prev != head && !prev->allocated) {prev->size += current->size;prev->next = current->next;free(current);current = prev;}if (current->next != NULL && !current->next->allocated) {current->size += current->next->size;partition_t* temp = current->next;current->next = current->next->next;free(temp);}return;}prev = current;current = current->next;}printf("Memory free failed\n");}int main() {// 初始化内存initialize(1000);// 分配内存int* p = (int*)allocate(sizeof(int));if (p != NULL) {*p = 10;}// 释放内存free_memory(p);return 0;}```在实际应用中,动态分区分配算法可能会使用更加复杂的内存分配方式,例如“首次适应算法”、“最佳适应算法”、“最坏适应算法”等。

编写程序实现动态分区存储管理方式的主存分配与回收 c语言

编写程序实现动态分区存储管理方式的主存分配与回收 c语言

编写程序实现动态分区存储管理方式的主存分配与回收 c语言以下是一个简单的 C 语言程序示例,实现了动态分区存储管理方式的主存分配与回收:```c#include <stdio.h>#include <stdlib.h>#define MAX_SIZE 1000typedef struct {int size;int address;} MemoryBlock;void allocateMemory(MemoryBlock *blockList, int size) {MemoryBlock *newBlock = (MemoryBlock *)malloc(sizeof(MemoryBlock));if (newBlock == NULL) {printf("内存分配失败\n");exit(1);}newBlock->size = size;newBlock->address = (blockList->address + size) % MAX_SIZE;blockList->address += size;newBlock->next = blockList->next;blockList->next = newBlock;}void freeMemory(MemoryBlock *blockList) {if (blockList->next == NULL) {printf("没有可释放的内存块\n");return;}MemoryBlock *current = blockList->next;blockList->next = current->next;free(current);}int main() {MemoryBlock *blockList = (MemoryBlock *)malloc(sizeof(MemoryBlock));if (blockList == NULL) {printf("内存分配失败\n");exit(1);}blockList->address = 0;blockList->next = NULL;// 内存分配allocateMemory(blockList, 100);allocateMemory(blockList, 200);allocateMemory(blockList, 300);// 输出分配的内存地址MemoryBlock *current = blockList->next;while (current != NULL) {printf("分配的内存大小: %d, 地址: %d\n", current->size, current->address);current = current->next;}// 内存回收freeMemory(blockList);// 输出剩余的内存地址current = blockList->next;while (current != NULL) {printf("剩余的内存大小: %d, 地址: %d\n", current->size,current->address);current = current->next;}freeblockList;return 0;}```上述程序中,我们定义了一个`MemoryBlock`结构体来表示内存块的信息,包括大小和地址。

操作系统课程设计动态异长分区的存储分配与回收算法

操作系统课程设计动态异长分区的存储分配与回收算法

操作系统课程设计——动态异长分区的存储分配与回收算法//该文件所含代码是课设需要学生自己写的代码和补充的代码,包含部分需要修改的课程设计指导书中的代码,不包含不需修改的代码//1.显示空闲区表void display_freearea_list(){FREEAREA *p;char buffer[20];p=p_free_area_list;printf("|--------------------|------------------|\n");printf("| start_address(kB) | size(KB) |\n");printf("|--------------------|------------------|\n");while(p!=NULL){printf("| %d",p->start_address);itoa( p->start_address, buffer, 10 );print_space(19-strlen(buffer));printf("| %d",p->size);itoa(p->size, buffer, 10 );print_space(17-strlen(buffer));printf("|\n");p=p->next;};printf("|--------------------|------------------|\n\n");}//2.最先适应分配法:内存释放函数void FF_release_memory(int start_address,int size){EnterCriticalSection(&CS_FREEAREA_LIST);__int64 t1, t2; //记录该算法起止时间t1 = GetCycleCount(); //记录起始时间FREEAREA *temp,*p,*pp;//将空闲区按start_address由小到大排序,以便整合相邻空闲区while(1){int change = 0;p = p_free_area_list;if(p->next != NULL){if(p->start_address > p->next->start_address){pp = p->next;p->next = pp->next;pp->next = p;操作系统课程设计——动态异长分区的存储分配与回收算法p_free_area_list = pp;change = 1;}}if(p->next != NULL){while(p->next->next != NULL){if(p->next->start_address > p->next->next->start_address ){pp = p->next->next;p->next->next = pp->next;pp->next = p->next;p->next = pp;change = 1;}p = p->next ;}}if(change == 0){break;}}//插入空闲区temp = new FREEAREA;p = new FREEAREA;temp->start_address = start_address;temp->size = size;temp->next = NULL;p->next = p_free_area_list;while(p->next != NULL){if(p->next->start_address > temp->start_address){temp->next = p->next ;p->next = temp;break;}else{p = p->next ;}}if(p->next == NULL){p->next = temp;}else if(temp->next == p_free_area_list){p_free_area_list = temp;}//整合碎片while(1){int change = 0;p = p_free_area_list;if(p == NULL){break;}while(p->next != NULL){if((p->start_address + p->size) == (p->next->start_address)){p->size = p->next->size + p->size;change = 1;if(p->next->next == NULL){free(p->next);p->next = NULL;}else{p->next = p->next->next;}}if(p->next == NULL){break;}else{p = p->next ;}}if(change == 0){break;}}//整理线程结束后的驻留链表THREAD_RESIDENCE_MEMORY *q;q = p_thread_residence_memory_list;if(q->start_address == start_address){p_thread_residence_memory_list = p_thread_residence_memory_list->next ; }else{while(q->next != NULL){if(q->next->start_address == start_address){if(q->next == tail_thread_residence_memory_list){tail_thread_residence_memory_list = q;}q->next = q->next->next ;break;}q = q->next;}}//记录结束时间,并将运行时间存入对应数组t2 = GetCycleCount();if(time[0][0] > t2 - t1){time[0][0] = t2 - t1;}if(time[0][1] < t2 - t1){time[0][1] = t2 - t1;}LeaveCriticalSection(&CS_FREEAREA_LIST);}//3.最佳适应分配算法的内存释放函数void BF_release_memory(int start_address,int size){EnterCriticalSection(&CS_FREEAREA_LIST);__int64 t1, t2; //记录该算法起止时间t1 = GetCycleCount(); //记录起始时间FREEAREA *temp,*p,*pp;//将空闲区按start_address由小到大排序,以便整合相邻空闲区while(1){int change = 0;p = p_free_area_list;if(p->next != NULL){if(p->start_address > p->next->start_address){pp = p->next;p->next = pp->next;pp->next = p;p_free_area_list = pp;change = 1;}}if(p->next != NULL){while(p->next->next != NULL){if(p->next->start_address > p->next->next->start_address ){pp = p->next->next;p->next->next = pp->next;pp->next = p->next;p->next = pp;change = 1;}p = p->next ;}}if(change == 0){操作系统课程设计——动态异长分区的存储分配与回收算法break;}}//插入空闲区temp = new FREEAREA;p = new FREEAREA;temp->start_address = start_address;temp->size = size;temp->next = NULL;p->next = p_free_area_list;while(p->next != NULL){if(p->next->start_address > temp->start_address){temp->next = p->next ;p->next = temp;break;}else{p = p->next ;}}if(p->next == NULL){p->next = temp;}else if(temp->next == p_free_area_list){p_free_area_list = temp;}//整合碎片while(1){int change = 0;p = p_free_area_list;if(p == NULL){break;}while(p->next != NULL){if((p->start_address + p->size) == (p->next->start_address)){p->size = p->next->size + p->size;change = 1;if(p->next->next == NULL){free(p->next);p->next = NULL;}else{p->next = p->next->next;}操作系统课程设计——动态异长分区的存储分配与回收算法}if(p->next == NULL){break;}else{p = p->next ;}}if(change == 0){break;}}//将空闲区按SIZE由小到大排序,以便符合BF算法while(1){int change = 0;p = p_free_area_list;if(p->size > p->next->size){pp = p->next;p->next = pp->next;pp->next = p;p_free_area_list = pp;change = 1;}while(p->next->next != NULL){if(p->next->size > p->next->next->size ){pp = p->next->next;p->next->next = pp->next;pp->next = p->next;p->next = pp;change = 1;}p = p->next ;}if(change == 0){break;}}//整理线程结束后的驻留链表THREAD_RESIDENCE_MEMORY *q;q = p_thread_residence_memory_list;if(q->start_address == start_address){p_thread_residence_memory_list = p_thread_residence_memory_list->next ; }else{操作系统课程设计——动态异长分区的存储分配与回收算法while(q->next != NULL){if(q->next->start_address == start_address){if(q->next == tail_thread_residence_memory_list){tail_thread_residence_memory_list = q;}q->next = q->next->next ;break;}q = q->next;}}//记录结束时间,并将运行时间存入对应数组t2 = GetCycleCount();if(time[1][0] > t2 - t1){time[1][0] = t2 - t1;}if(time[1][1] < t2 - t1){time[1][1] = t2 - t1;}LeaveCriticalSection(&CS_FREEAREA_LIST);}//4.最坏适应分配算法:内存释放函数void WF_release_memory(int start_address,int size){EnterCriticalSection(&CS_FREEAREA_LIST);__int64 t1, t2; //记录该算法起止时间t1 = GetCycleCount(); //记录起始时间FREEAREA *temp,*p,*pp;//将空闲区按start_address由小到大排序,以便整合相邻空闲区while(1){int change = 0;p = p_free_area_list;if(p->next != NULL){if(p->start_address > p->next->start_address){pp = p->next;p->next = pp->next;pp->next = p;p_free_area_list = pp;change = 1;}}if(p->next != NULL){操作系统课程设计——动态异长分区的存储分配与回收算法while(p->next->next != NULL){if(p->next->start_address > p->next->next->start_address ){pp = p->next->next;p->next->next = pp->next;pp->next = p->next;p->next = pp;change = 1;}p = p->next ;}}if(change == 0){break;}}//插入空闲区temp = new FREEAREA;temp->start_address = start_address;temp->size = size;temp->next = NULL;p = new FREEAREA;p->next = p_free_area_list;while(p->next != NULL){if(p->next->start_address > temp->start_address){temp->next = p->next ;p->next = temp;break;}else{p = p->next ;}}if(p->next == NULL){p->next = temp;}else if(temp->next == p_free_area_list){p_free_area_list = temp;}//整合碎片while(1){int change = 0;p = p_free_area_list;if(p == NULL){break;操作系统课程设计——动态异长分区的存储分配与回收算法}while(p->next != NULL){if((p->start_address + p->size) == (p->next->start_address)){p->size = p->next->size + p->size;change = 1;if(p->next->next == NULL){free(p->next);p->next = NULL;}else{p->next = p->next->next;}}if(p->next == NULL){break;}else{p = p->next ;}}if(change == 0){break;}}//将空闲区按SIZE由大到小排序,以便符合WF算法while(1){int change = 0;p = p_free_area_list;if(p->size < p->next->size){pp = p->next;p->next = pp->next;pp->next = p;p_free_area_list = pp;change = 1;}while(p->next->next != NULL){if(p->next->size < p->next->next->size ){pp = p->next->next;p->next->next = pp->next;pp->next = p->next;p->next = pp;change = 1;}p = p->next ;}操作系统课程设计——动态异长分区的存储分配与回收算法if(change == 0){break;}}//整理线程结束后的驻留链表THREAD_RESIDENCE_MEMORY *q;q = p_thread_residence_memory_list;if(q->start_address == start_address){p_thread_residence_memory_list = p_thread_residence_memory_list->next ;}else{while(q->next != NULL){if(q->next->start_address == start_address){if(q->next == tail_thread_residence_memory_list){tail_thread_residence_memory_list = q;}q->next = q->next->next ;break;}q = q->next;}}//记录结束时间,并将运行时间存入对应数组t2 = GetCycleCount();if(time[2][0] > t2 - t1){time[2][0] = t2 - t1;}if(time[2][1] < t2 - t1){time[2][1] = t2 - t1;}LeaveCriticalSection(&CS_FREEAREA_LIST);}//5.二维数组,用于存放各种算法所需的最长时间和最短时间__int64 time[3][2] = {{99999999,0},{99999999,0},{99999999,0}};//6.显示程序运行时间void display_time(int n){EnterCriticalSection(&CS_SCREEN);printf("最短时间:%ld纳秒\n",time[n][0]);操作系统课程设计——动态异长分区的存储分配与回收算法printf("最长时间:%ld纳秒\n",time[n][1]);LeaveCriticalSection(&CS_SCREEN);}//7.在FF()、BF()、WF()中的删除各链表操作前加入以下代码void FF(){………………//显示线程结束后的空闲区EnterCriticalSection(&CS_SCREEN);printf("空闲区:\n");display_freearea_list();LeaveCriticalSection(&CS_SCREEN);//显示该算法所需时间display_time(0);//删除各种链表………………}void BF(){………………//显示线程结束后的空闲区EnterCriticalSection(&CS_SCREEN);printf("空闲区:\n");display_freearea_list();LeaveCriticalSection(&CS_SCREEN);//显示该算法所需时间display_time(1);//删除各种链表………………}void WF(){………………//显示线程结束后的空闲区操作系统课程设计——动态异长分区的存储分配与回收算法EnterCriticalSection(&CS_SCREEN);printf("空闲区:\n");display_freearea_list();LeaveCriticalSection(&CS_SCREEN);//显示该算法所需时间display_time(2);//删除各种链表………………}//8.设置计算时间的函数RDTSC方法__inline unsigned __int64 GetCycleCount(){__asm _emit 0x0F__asm _emit 0x31}//9.获取当前时间t = GetCycleCount();主界面:FF的运行结果BF的运行结果WF的运行结果。

计算机操作系统动态分区存储管理方式下的内存空间的分配与回收实验报告

计算机操作系统动态分区存储管理方式下的内存空间的分配与回收实验报告

计算机操作系统动态分区存储管理方式下的内存空间的分配与回收实验报告第一篇:计算机操作系统动态分区存储管理方式下的内存空间的分配与回收实验报告计算机操作系统实验报告实验二实验题目:存储器管理系别:计算机科学与技术系班级:姓名:学号:2一、实验目的深入理解动态分区存储管理方式下的内存空间的分配与回收。

二、实验内容编写程序完成动态分区存储管理方式下的内存分配和回收的实现。

具体内容包括:确定用来管理内存当前使用情况的数据结构;采用首次适应算法完成内存空间的分配;分情况对作业进行回收;编写主函数对所做工作进行测试。

三、实验原理分配:动态分区存储管理方式把内存除OS占用区域外的空间看作一个大的空闲区。

当作业要求装入内存时,根据作业需要内存空间的大小查询内存中各个空闲区,当从内存中找到一个大于或等于该作业大小的内存空闲区时,选择其中一个空闲区,按作业要求划出一个分区装入该作业。

回收:作业执行完后,它所占用的内存空间被收回,成为一个空闲区。

如果该空闲区的相邻分区也是空闲区,则需要将相邻空闲区合并成一个空闲区。

四、实验方法实现动态分区的分配与回收,主要考虑三个问题:第一、设计记录内存使用情况的数据表格,用来记录空闲区和作业占用的区域(利用结构体类型数组来保存数据);第二、在设计的数据表格基础上设计内存分配算法(采用首次适应算法找合适的分区(对空闲分区表进行排序),分配时要考虑碎片问题);第三、在设计的数据表格基础上设计内存回收算法(分四种情况进行回收(上邻、下邻、上下邻和无相邻分区)。

五、实验步骤第一,设计记录内存使用情况的数据表格λ已分配分区表:起始地址、长度、标志(0表示“空表项”,1表示“已分配”)λ空闲分区表:起始地址、长度、标志(0表示“空表项”,1表示“未分配”)struct used_table { float address;//已分分区起始地址float length;//已分分区长度,单位为字节int flag;//已分配表区登记栏标志,用0表示空栏目,char zuoyename;};//已分配区表Struct free_table[ { float address;//空闲分区起始地址float length;//空闲分区长度,单位为字节int flag;//空闲分区表登记栏目用0表示空栏目,1表示未配};//空闲分区表第二,在设计的表格上进行内存分配λ首次适应算法:为作业分配内存,要求每次找到一个起始地址最小的适合作业的分区(按起始地址递增排序)。

操作系统-实验四动态分区分配算法源代码最全(可编辑)

操作系统-实验四动态分区分配算法源代码最全(可编辑)

操作系统-实验四动态分区分配算法源代码最全(可编辑)实验四操作系统-动态分区分配算法萨斯的发生的v设计程序模拟四种动态分区分配算法:首次适应算法、循环首次适应算法、最佳适应算法和最坏适应算法的工作过程。

假设内存中空闲分区个数为n,空闲分区大小分别为P1, … ,Pn,在动态分区分配过程中需要分配的进程个数为m(m?n),它们需要的分区大小分别为S1, … ,Sm,分别利用四种动态分区分配算法将m个进程放入n个空闲分区,给出进程在空闲分区中的分配情况。

程序要求如下:1)利用首次适应算法、循环首次适应算法、最佳适应算法和最坏适应算法四种动态分区分配算法模拟分区分配过程。

2)模拟四种算法的分区分配过程,给出每种算法进程在空闲分区中的分配情况。

3)输入:空闲分区个数n,空闲分区大小P1, … ,Pn,进程个数m,进程需要的分区大小S1, … ,Sm,算法选择1-首次适应算法,2-循环首次适应算法,3-最佳适应算法,4-最坏适应算法。

4)输出:最终内存空闲分区的分配情况。

代码实现:#include#include#includeusing namespace std;const int Number100; int FreePartition[Number];//空闲分区大小 int FirstPartition[Number];//1-首次适应算法 intCycleFirstPartition[Number];//2-循环首次适应算法 intBestPartition[Number];//3-最佳适应算法 int WorstPartition[Number];//4-最坏适应算法 int ProcessNeed[Number];//进程需要的分区大小 int PartitionNum,ProcessNum; char ProcessName[Number];//进程名char ProcessPartition[Number];//进程分配的序列 int Partition[Number]; char str[Number][Number]; void FirstFitint n,int m; void NextFitintn,int m; void BestFitint n,int m; void WorstFitint n,int m; voidPrintint n, int m; void Print2int n, int m; //void FirstFitint n, int m cout"选择了首次适应算法!"endl;coutendl;int i,j,k0;fori0; in; i++FirstPartition[i] FreePartition[i]; forj0; jm; j++fori0; in; i++ifProcessNeed[j]FirstPartition[i] ProcessPartition[j]i;//str[i][k] ProcessName[j];FirstPartition[i] FirstPartition[i]-ProcessNeed[j];break;Printn,m;cout"空间序号:"" ";fori0; in; i++cout"|"setwm-1"空间"i+1;coutendl;cout"分区大小:"" ";fori0; in; i++cout"|"setwmsetiosflagsios::leftFreePartition[i];coutendl;cout"剩余分区大小:";fori0; in; i++cout"|"setwmsetiosflagsios::leftFirstPartition[i];coutendl;Print2n,m;void NextFitint n, int m cout"选择了循环首次适应算法!"endl; coutendl;int i,j,flag0;fori0; in; i++CycleFirstPartition[i] FreePartition[i];forj0; jm; j++foriflag; in; i++ifProcessNeed[j]CycleFirstPartition[i]ProcessPartition[j]i; CycleFirstPartition[i] CycleFirstPartition[i]-ProcessNeed[j];flag i+1;ifin-1flag0;break;Printn,m;cout"空间序号:"" ";fori0; in; i++cout"|"setwm-1"空间"i+1;coutendl;cout"分区大小:"" ";fori0; in; i++cout"|"setwmsetiosflagsios::leftFreePartition[i]; coutendl;cout"剩余分区大小:";fori0; in; i++cout"|"setwmsetiosflagsios::leftCycleFirstPartition[i]; coutendl;Print2n,m;void BestFitint n, int mcout"选择了最佳适应算法!"endl;coutendl;int i,j,flag0,temp,id0,flag10; fori0; in; i++ BestPartition[i] FreePartition[i]; whileflag1mflag 0;fori0; in; i++Partition[i]0;fori0; in; i++ifProcessNeed[flag1]BestPartition[i] Partition[flag]i; flag + 1;temp BestPartition[Partition[0]]; id Partition[0]; fori1;iflag; i++ iftemp BestPartition[Partition[i]] temp BestPartition[Partition[i]];id Partition[i];BestPartition[id]BestPartition[id]-ProcessNeed[flag1];ProcessPartition[flag1]id; flag1 + 1;Printn,m;cout"空间序号:"" ";fori0; in; i++cout"|"setwm-1"空间"i+1;coutendl;cout"分区大小:"" ";fori0; in; i++cout"|"setwmsetiosflagsios::leftFreePartition[i]; coutendl;cout"剩余分区大小:";fori0; in; i++cout"|"setwmsetiosflagsios::leftBestPartition[i]; coutendl;Print2n,m;void WorstFitint n, int mcout"选择了最坏适应算法!"endl;coutendl;int i,j,flag0,temp,id0,flag10;fori0; in; i++WorstPartition[i] FreePartition[i];whileflag1mflag 0;fori0; in; i++Partition[i]0;fori0; in; i++ifProcessNeed[flag1]WorstPartition[i]Partition[flag]i;flag + 1;temp WorstPartition[Partition[0]]; id Partition[0]; fori1;iflag; i++ ifWorstPartition[Partition[i]] temp temp WorstPartition[Partition[i]];id Partition[i];WorstPartition[id]WorstPartition[id]-ProcessNeed[flag1];ProcessPartition[flag1]id; flag1 + 1;Printn,m;cout"空间序号:"" ";fori0; in; i++cout"|"setwm-1"空间"i+1;coutendl;cout"分区大小:"" ";fori0; in; i++cout"|"setwmsetiosflagsios::leftFreePartition[i];coutendl;cout"剩余分区大小:";fori0; in; i++cout"|"setwmsetiosflagsios::leftWorstPartition[i];coutendl;Print2n,m;void choiceint n, int m int intput;cout"\n请选择:1.首次适应算法 2.循环首次适应算法 3.最佳适应算法 4. 最坏适应算法:"endl;cinintput;coutendl;switchintputcase 1:FirstFitn,m;choicen,m;break;case 2:NextFitn,m;choicen,m;break;case 3:BestFitn,m;choicen,m;break;case 4:WorstFitn,m; choicen,m;break;coutendl;void Printint n, int mint j;cout"进程名:";forj0; jm; j++ cout"|"setwmsetiosflagsios::leftProcessName[j]; coutendl;cout"进程分区大小:";forj0; jm; j++ cout"|"setwmsetiosflagsios::leftProcessNeed[j]; coutendl;cout"分配结果:"endl;void Print2int n, int m int i,j;fori0; in; i++forj0; jm; j++str[i][j] 0;cout"进程分配分区:";fori0; in; i++int k0;forj0; jm; j++ifProcessPartition[j]i str[i][k] ProcessName[j];k + 1;fori0; in; i++cout"|";forj0; jm; j++coutsetw1str[i][j]; coutendl;//void mainifstream in"yin.txt"; int n,m;int i,j;inn;fori0; in; i++ inFreePartition[i]; inm;forj0; jm; j++ inProcessName[j]; forj0; jm; j++ inProcessNeed[j]; choicen,m;运行结果:。

操作系统实验动态分区存储管理方式的主存分配回收.

操作系统实验动态分区存储管理方式的主存分配回收.

操作系统实验_动态分区存储管理方式的主存分配回收//////////////////////////////////////////////////////////// // 功能:// 《计算机操作系统》实验// 首次适应性算法// 摸拟动态分区存储管理方式的主存分配和回收// 时间:// 2005-11-14////////////////////////////////////////////////////////////#include "iostream.h"#include "iomanip.h"#define ERR_NOFREEAREA 1#define ERR_NOADEQUACYAREA 2#define ERR_ALLOCATED 4#define ERR_NOJOBS 1#define ERR_NOSUCHJOB 2#define ERR_RECLAIMED 4typedef struct tagUsedNode{long address;long length;int flag; //作业名struct tagUsedNode *next;} USED_AREA , *USED_TABLE;typedef struct tagFreeNode{long address;long length;struct tagFreeNode *next;} FREE_AREA , *FREE_TABLE;//空闲区、作业区链表USED_TABLE usedTable = NULL;FREE_TABLE freeTable = NULL;//给作业分配空间//jobname: 作业名//jobsize: 作业所需空间大小int Allocate( int jobname , long jobsize )//如果没有空闲区if( freeTable == NULL )return ERR_NOFREEAREA;FREE_TABLE p = freeTable;FREE_TABLE q = p;//找首次适应空闲区while( p != NULL && p->length < jobsize ){q = p;p = p->next;}//如果找不到有足够空间的分区if( p == NULL )return ERR_NOADEQUACYAREA;USED_TABLE x = new USED_AREA;x->address = p->address;x->length = jobsize;x->flag = jobname;x->next = NULL;//如果该分区大于作业需求,空间大小减去作业大小if( p->length > jobsize ){p->length -= jobsize;p->address += jobsize;}//如果该分区等于作业大小,删除该分区else{if( p == freeTable )freeTable = NULL;elseq->next = p->next;delete p;}//作业加入“作业表”中USED_TABLE r = usedTable;USED_TABLE t = r;while( r != NULL && r->address < x->address ) {t = r;r = r->next;}if( usedTable == NULL )usedTable = x;else{x->next = r;t->next = x;}return ERR_ALLOCATED;}//回收作业空间//jobname: 作业名int Reclaim( int jobname ){if( usedTable == NULL )return ERR_NOJOBS;USED_TABLE p = usedTable;USED_TABLE q = p;while( p != NULL && p->flag != jobname ){q = p;p = p->next;}//如果没有该作业if( p == NULL )return ERR_NOSUCHJOB;//回收后的空间加入到空闲区FREE_TABLE r = freeTable;FREE_TABLE t = r;FREE_TABLE x;while( r != NULL && r->address < p->address ) {t = r;r = r->next;}x = new FREE_AREA;x->address = p->address;x->length = p->length;x->next = NULL;if( r == freeTable ){x->next = r;freeTable = x;t = freeTable;}else{x->next = r;t->next = x;}//合并分区while( t->next != NULL && t->address + t->length == t->next->address ) {t->length += t->next->length;r = t->next;t->next = t->next->next;delete r;}//删除该作业if( p == usedTable ){usedTable = usedTable->next;}elseq->next = p->next;delete p;return ERR_RECLAIMED;}int Init(){freeTable = new FREE_AREA;freeTable->address = 0;freeTable->length = 1024;freeTable->next = NULL;return 1;}void jobrequest(){int jobname;int jobsize;cout<<"...................."<<endl;cout<<"作业名: ";cin >> jobname;cout<<"作业长度: ";cin >> jobsize;if( Allocate( jobname , jobsize ) == ERR_ALLOCATED )cout<<"该作业已成功获得所需空间"<<endl;elsecout<<"该作业没有获得所需空间"<<endl;cout<<"...................."<<endl;}void jobreclaim(){int jobname;cout<<"...................."<<endl;cout<<"作业名: ";cin >>jobname;int result = Reclaim( jobname );if( result == ERR_RECLAIMED )cout<<"该作业已成功回收"<<endl;else if( result == ERR_NOSUCHJOB || result == ERR_NOJOBS )cout<<"系统没有作业或该作业不存在"<<endl;cout<<"...................."<<endl;}void freeTablePrint(){cout<<"........................................"<<endl;cout<<setw(10)<<"address"<<setw(10)<<"length"<<setw(10)<<"state"<<en dl<<endl;FREE_TABLE p = freeTable;USED_TABLE q = usedTable;int x , y;while( p || q ){if( p )x = p->address;elsex = 0x7fffffff;if( q )y = q->address;elsey = 0x7fffffff;if( x < y ){cout<<setw(10)<<p->address<<setw(10)<<p->length<<setw(10)<<"空闲"<<endl;p = p->next;}if( x > y ){cout<<setw(10)<<q->address<<setw(10)<<q->length<<setw(10)<<"已分配"<<setw(10)<<"ID="<<q->flag<<endl;q = q->next;}}cout<<"........................................"<<endl;}void main(){Init();int choose;bool exitFlag = false;while( !exitFlag ){cout<<"选择功能项( 0 -退出 1 - 分配主存 2 - 回收主存 3 - 显示主存)"<<endl; cout<<"?>";cin>>choose;switch( choose ){case 0:exitFlag = true;break;case 1:jobrequest();break;case 2:jobreclaim();break;case 3:freeTablePrint();break;}}}Trackback: /TrackBack.aspx?PostId=529025。

《操作系统》实验报告2 可变分区存储管理方式的内存分配回收

《操作系统》实验报告2 可变分区存储管理方式的内存分配回收
printf("选?择?功|能¨¹项?(ꡧ0~3)ê?:êo");
scanf("%d",&a);
switch(a)
{case0;exit(0);
case1;
printf ("输º?入¨?作Á¡Â业°¦Ì名?J和¨ª作Á¡Â业°¦Ì所¨´需¨¨长¡è度¨¨xk:êo");
scanf("%*c%c%f",&J,&xk);
实验项目
名称
可变分区存储管理方式的内存分配回收
实验
目的及要求
1、深入了解采用可变分区存储管理方式的内存分配回收的实现
实验
内容
编写程序完成可变分区存储管理方式的内存分配回收
实验步骤
1、确定内存空间分配表
2、采用最优适应算法完成内存空间的分配和回收
3、编写主函数对所做工作进行测试
实验环境
Windows XP、visualstudio 2005
}
i++;
}
if(k!=-1)
if(j!=1)
{free_table[k].length=free_table[j].length+free_table[k].length+L;
free_table[j].flag=0;
}
else
free_table[k].length=free_table[k].length+L;
L=used_table[s].length;
j==1;k=-1;i=0;
while(i<m&&(j==-1||k==-1))
{
if(free_table[i].glag==0)

操作系统内存的分配与回收

操作系统内存的分配与回收

printf(”\nl:分配主存\n");scanf(,,%d ,,,&choose); switch(choose) case 1:printf("\n 请输入作业所需长度xk:");scanf(“%f”,&xkO);#defineminisize100 #definen4 #definem4 #include<stdio.h>/*空闲区一申请空间Wminisize 时,分配整个空闲区*/ /*假定系统允许的最大作业为n,假定模拟实验中n 值为10*/ /*假定系统允许的空闲区表最大为m*//*系统中主要数据结构*/ struct floataddress; floatlength;int flag; }free_table[m]; /*空闲区起始地址*//*空闲区长度,单位为字节*//*空闲区表登记栏标记,用0表示空栏目,用1表示未分配*/ /*空闲区表*/struct{ floataddress; floatlength;i ntflag; }used_table[n]; /*已分分区起始地址*/ /*已分区长度,单位为字节*//*已分配区表登记栏标志,用“0”表示空栏目*//*已分配区表*/voidmain() float S OJO; inti; intchoose; voidreclaim(floats,floatI); voidreclaiml(floatsjloatI); floatallocate(floatxk); floatxk0,ad0;free_table[0].address=10240; free_table[0].length=102400; free_table[O].flag=l; for(i=l;i<m;i++)free_table[i].flag=O; for(i=0;i<n;i++)used_table[i].flag=O; while(l)〃分配主存空间函数〃空闲区表初始化 〃已分配表初始化 2:回收主存3:显示主存4:退出5:回收已经使用分区adO=allocate(xkO);break;case 2:printf(“输入要回收的起始地址与分区长度门;scanf(',%f%f,,/&sO,&IO);reclaim(sOjO);break;case 3:printf("空闲区表:\n“);if(adO){printf("序号\t\t起始地址\t\t尺寸\t\t状态\t\n");for(i=0;i<m;i++)(printf("%d\t\t",i);printf(,,%f\t\t,,/free_table[i].address);printf(,,%f\t\t,,/free_table[i].length);printf(,,%d\t\t\n,\free_table[i].flag);)printf("\n已分配表:\n");printf("序号\t\t起始地址\t\t尺寸\t\t状态\t\n");for(i=0;i<n;i++)(if(used_table[i].flag!=O)(printf("%d\t\t",i);printf(,,%f\t\t l,,used_table[i].address);printf(,,%f\t\t l,,used_table[i].length);printf(,,%d\t\t\n"/used_table[i].flag);;)else(printf("%d\t\t",i);printf(,,%f\t\t l,,used_table[i].address);printf(,,%f\t\t l,,used_table[i].length);printf(,,%d\t\t\n"/used_table[i].flag);)}//for}//ifbreak;case 4:exit(O);default:printf("无此项,请重新选择!”);}//switch}//while(l))floatallocate(floatxk)〃分配函数(intiJk;floatad;k=-l;〃k=-l,分配不成功for(i=0;i<m;i++)/*寻找空间大于xk的最小空闲空间登记项k*/{if((free_table[i].length>=xk)&&(free_table[ij.flag==l)){k=i;break;)}if(k==-l)/*无可用空闲区,返回*/{printf(H nofreespace\n H);return(-l);}else{for(j=0;j<n;j++){if(used_table[j].flag==O){if((free_table[k].length-xk)<=minisize)/*找到可用空闲区,开始分配*/(used_table[j].length=free_table[k].length;used_table[j].address=free_table[k].address;used_table[j].flag=l;free_table[k].flag=O;ad=free_table[k].address;xk=free_table[k].length;)else(used_table[j].address=free_table[k].address+free_table[k].length-xk;used_table[j].flag=l;used_table[j].length=xk;free_table[k].length=free_table[k].length-xk;ad=free_table[k].address+free_table[k].length;)return(ad);}//if}//for(//else)voidreclaim(floats,floatI)〃回收空闲区表(intij,k,t;j=-l;k=-l;i=O;/*寻找回收分区的空闲上下邻,上邻表目为k,下邻表目为j*/while(i<m&&(j==-l11k==-l))(if(free_table[i].address+free_table[i].length==s)k=i;if(free_table[i].address==s+l)j=i;i++;break;)if(k!=-l)(if(j!=-l)/*上邻空闲区,下邻空闲区,三项合并*/{free_table[k].length=free_table[j].length+free_table[k].length+l;free_table[j].flag=0;)else/*上邻空闲区,下邻非空闲区,与上邻合并*/(free_table[k].length=free_table[k].length+l;used_table[k].flag=O;used_table[k].length=O;used_table[k].address=O;))else(if(j!=-l)/*上邻非空闲区,下邻空闲区,与下邻合并*/{free_table[j].address=s;free_table[j].length=free_table[j].length4-l;free_table[j].flag=l;used_table[j].flag=O;used_table[j].length=O;used_table[j].address=O;printf("\n已回收!\n");)else/*上下均邻非空闲区,回收区域直接填入*/(t=0;while(free_table[t].flag==l&&t<m)/*在空闲区表中寻找空栏目*/t++;/*显示主存空闲区表没有空间,回收空间失败*/(printf("Nofreespacetableline,fail!\n");return;))free_table[t].address=s;free_table[t].length=l;free_table[t].flag=l;used_table[t].length=O;used_table[t].flag=O;used_table[t].address=O;)}初始状态:分配三个主存:分配一个大小为253:分配一个大小为90:分配一个大小为30:此时的状态为:回收:回收90:。

动态分区存储管理的分配与回收代码

动态分区存储管理的分配与回收代码

#include<iostream>using namespace std;//#define MAX_LEN 1024//定义内存大小,1024字节enum Status{FREE,BUSY,OK,ERROR};struct PST{//partition specification tableint ID;//分区号int addr;//起始地址int size;//分区长度Status state;//状态};struct Node{//双向链表结点PST data;Node *back;//前驱Node *next;//后继Node(){back=NULL;next=NULL;}Node(int id,int size){data.ID=id;data.size=size;back=NULL;next=NULL;}};int area;//输入内存空间Node *head,*last;void Init(int area){head=new Node();last=new Node();head->next=last;last->back=head;last->data.addr=0;last->data.ID=0;last->data.size=area;last->data.state=FREE;}Status FFA(int id,int size){//head fit algorithmNode *temp=new Node(id,size);temp->data.state=BUSY;Node *cur=head->next;while(cur){if(cur->data.state==FREE&&cur->data.size==size){//如果空闲块大小刚好与请求大小相等,直接分配cur->data.ID=id;cur->data.state=BUSY;return OK;break;}if(cur->data.state==FREE&&cur->data.size>size){//如果大于temp->back=cur->back;temp->next=cur;cur->back->next=temp;temp->data.addr=cur->data.addr;cur->back=temp;cur->data.addr=cur->data.addr+size;cur->data.size=cur->data.size-size;return OK;break;}cur=cur->next;}return ERROR;}Status BFA(int id,int size){//best fit algorithmNode *temp=new Node(id,size);temp->data.state=BUSY;int min;//记录符合满足请求的最小空闲块大小Node *fit;//指向采用最佳适应算法的插入位置Node *cur=head->next;while(cur){//取得第一个可以分配的位置(不一定是最佳位置)if(cur->data.state==FREE&&cur->data.size>=size){fit=cur;min=cur->data.size-size;break;}cur=cur->next;}while(cur){if(cur->data.state==FREE&&cur->data.size==size) {//如果相等直接分配cur->data.state=BUSY;cur->data.ID=id;return OK;break;}if(cur->data.state==FREE&&cur->data.size>size){//获取最佳位置if(cur->data.size-size<min){min=cur->data.size-size;fit=cur;}}cur=cur->next;}if(fit){//若最佳,插入temp->back=fit->back;temp->next=fit;fit->back->next=temp;temp->data.addr=fit->data.addr;fit->back=temp;fit->data.addr=fit->data.addr+size;fit->data.size=fit->data.size-size;return OK;}elsereturn ERROR;}Status WFA(int id,int size){//worst fit algorithmNode *temp=new Node(id,size);temp->data.state=BUSY;int max;//记录符合满足请求的最小空闲块大小Node *fit;//指向采用最坏适应算法的插入位置Node *cur=head->next;while(cur){//取得第一个可以分配的位置(不一定是最佳位置)if(cur->data.state==FREE&&cur->data.size>=size){fit=cur;max=cur->data.size-size;break;}cur=cur->next;}while(cur){/*if(cur->data.state==FREE&&cur->data.size==size) {//如果相等直接分配cur->data.state=BUSY;cur->data.ID=id;return OK;break;}*/if(cur->data.state==FREE&&cur->data.size>size){//获取最佳位置if(cur->data.size-size>max){max=cur->data.size-size;fit=cur;}}cur=cur->next;}if(fit){//若最佳,插入temp->back=fit->back;temp->next=fit;fit->back->next=temp;temp->data.addr=fit->data.addr;fit->back=temp;fit->data.addr=fit->data.addr+size;fit->data.size=fit->data.size-size;return OK;}elsereturn ERROR;}void Free(int id){Node *cur=head;while(cur){if(cur->data.ID==id){cur->data.state=FREE;cur->data.ID=FREE;if(cur->back->data.state==FREE)//与前面的空闲块相连{cur->back->data.size+=cur->data.size;cur->back->next=cur->next;cur->next->back=cur->back;}if(cur->next->data.state==FREE)//与后面的空闲块相连{cur->data.size+=cur->next->data.size;cur->next->next->back=cur->back;cur->back->next=cur->next;}break;}cur=cur->next;}}Status Assign(int choice){int id,size;cout<<"请输入区号:";cin>>id;cout<<endl<<"请输入分区长度(KB):";cin>>size;if(size<=0){cout<<"输入错误!"<<endl;return ERROR;}if(choice==1){if(FFA(id,size)==OK)cout<<"分配成功!"<<endl;elsecout<<"分配失败!"<<endl;}else if(choice==2){if(BFA(id,size)==OK)cout<<"分配成功!"<<endl;elsecout<<"分配失败!"<<endl;}else if(choice==3){if(WFA(id,size)==OK)cout<<"分配成功!"<<endl;elsecout<<"分配失败!"<<endl;}elsereturn ERROR;}void Show(){Node *cur=head->next;while(cur){cout<<"***********************************"<<endl;cout<<"区号:";if(cur->data.ID==FREE)cout<<"无"<<endl;elsecout<<cur->data.ID<<endl;cout<<"起始地址:"<<cur->data.addr<<endl;cout<<"分区长度:"<<cur->data.size<<endl;cout<<"状态:";if(cur->data.state==BUSY)cout<<"已分配"<<endl;elsecout<<"未分配"<<endl;cur=cur->next;}}int main(){cout<<" 动态分区分配方式的模拟"<<endl;cout<<"********************************************"<<endl;cout<<"请输入内存大小(KB):";cin>>area;while(area<=0){cout<<"输入错误,请重新输入内存大小(KB)";cin>>area;}while(1){cout<<"********************************************"<<endl;cout<<"** 1.FFA 2.BFA 3.WFA 0.EXIT **"<<endl;cout<<"********************************************"<<endl;cout<<"请选择:";int ch;cin>>ch;if(ch==0){break;}Init(area);int choice;while(1){cout<<"********************************************"<<endl;cout<<"** 1.ASSIGN 2.FREE 3.SHOW 0.QUIT **"<<endl;cout<<"****************************************** **"<<endl;cout<<"请输入您的操作:";cin>>choice;if(choice==1){cout<<"请输入进程个数";int num;cin>>num;for(;num>0;num--){Assign(ch);}}else if(choice==2){int ID;cout<<"请输入您要释放的分区号:";cin>>ID;Free(ID);}else if(choice==3) Show();else if(choice==0) break;else{cout<<"输入有误,请重试!"<<endl;continue;}}}return 0;}。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

存储管理动态分区分配及回收算法课程名称:计算机操作系统班级:信1501-2实验者姓名:李琛实验日期:2018年5月20日评分: 教师签名:一、实验目的分区管理就是应用较广泛的一种存储管理技术。

本实验要求用一种结构化高级语言构造分区描述器,编制动态分区分配算法与回收算法模拟程序,并讨论不同分配算法的特点。

二、实验要求1、编写:First Fit Algorithm2、编写:Best Fit Algorithm3、编写:空闲区回收算法三、实验过程(一)主程序1、定义分区描述器node,包括3 个元素:(1)adr——分区首地址(2)size——分区大小(3)next——指向下一个分区的指针2、定义3 个指向node 结构的指针变量:(1)head1——空闲区队列首指针(2)back1——指向释放区node 结构的指针(3)assign——指向申请的内存分区node 结构的指针3、定义1 个整形变量:free——用户申请存储区的大小(由用户键入)(二)过程1、定义check 过程,用于检查指定的释放块(由用户键入)的合法性2、定义assignment1 过程,实现First Fit Algorithm3、定义assignment2 过程,实现Best Fit Algorithm4、定义acceptment1 过程,实现First Fit Algorithm 的回收算法5、定义acceptment2 过程,实现Best Fit Algorithm 的回收算法6、定义print 过程,打印空闲区队列(三)执行程序首先申请一整块空闲区,其首址为0,大小为32767;然后,提示用户使用哪种分配算法,再提示就是分配还就是回收;分配时要求输入申请区的大小,回收时要求输入释放区的首址与大小。

实验代码Main、cpp#include<stdio、h>#include<stdlib、h>#include<string、h>#include<iostream>using namespace std;#define MAX_SIZE 32767typedef struct node{int id;int adr;int size;struct node *next;}Node;Node *head1, *head2, *back1, *back2, *assign;int request;int check(int add, int siz, char c){Node *p, *head;int check = 1;if (add<0 || siz<0)check = 0;/*地址与大小不能为负*/if (c == 'f' || c == 'F')head = head1;elsehead = head2;p = head->next;while ((p != NULL) && check)if (((add<p->adr) && (add + siz>p->adr)) || ((add >= p->adr) && (add<p->adr + p->size))) check = 0;elsep = p->next;if (check == 0)printf("\t输入释放区地址或大小有错误!!!\n");return check;}void init(){Node *p;head1 = (Node*)malloc(sizeof(Node));head2 = (Node*)malloc(sizeof(Node));p = (Node*)malloc(sizeof(Node));head1->next = p;head2->next = p;p->size = MAX_SIZE;p->adr = 0;p->next = NULL;p->id = 0;}Node* assignment1(int num, int req){Node *before, *after, *ass;ass = (Node*)malloc(sizeof(Node));before = head1;after = head1->next;ass->id = num;ass->size = req;while (after->size<req){before = before->next;after = after->next;}if (after == NULL){ass->adr = -1;}else{if (after->size == req){before->next = after->next;ass->adr = after->adr;}else{after->size -= req;ass->adr = after->adr;after->adr += req;}}return ass;}void acceptment1(int address, int siz, int rd) {Node *before, *after;int insert = 0;back1 = (Node*)malloc(sizeof(Node));before = head1;after = head1->next;back1->adr = address;back1->size = siz;back1->id = rd;back1->next = NULL;while (!insert&&after){//将要被回收的分区插入空闲区(按首址大小从小到大插入)if ((after == NULL) || ((back1->adr <= after->adr) && (back1->adr >= before->adr))){before->next = back1;back1->next = after;insert = 1;}else{before = before->next;after = after->next;}}if (insert){if (back1->adr == before->adr + before->size){//与前边分区合并before->size += back1->size;before->next = back1->next;free(back1);}else if (after&&back1->adr + back1->size == after->adr){//与后边分区合并back1->size += after->size;back1->next = after->next;back1->id = after->id;free(after);after = back1;}printf("\t首先分配算法回收内存成功!\n");}elseprintf("\t首先分配算法回收内存失败!\n");}Node* assignment2(int num, int req){Node *before, *after, *ass, *q;ass = (Node*)malloc(sizeof(Node));q = (Node*)malloc(sizeof(Node));before = head2;after = head2->next;ass->id = num;ass->size = req;while (after->size<req){before = before->next;after = after->next;}if (after == NULL){ass->adr = -1;}else{if (after->size == req){before->next = after->next;ass->adr = after->adr;}else{q = after;before->next = after->next;ass->adr = q->adr;q->size -= req;q->adr += req;before = head2;after = head2->next;if (after == NULL){before->next = q;q->next = NULL;}else{while ((after->size)<(q->size)){before = before->next;after = after->next;}before->next = q;q->next = after;}}}return (ass);}void acceptment2(int address, int siz, int rd){Node *before, *after;int insert = 0;back2 = (Node*)malloc(sizeof(Node));before = head2;after = head2->next;back2->adr = address;back2->size = siz;back2->id = rd;back2->next = NULL;if (head2->next == NULL){//空闲队列为空head2->next = back2;head2->size = back2->size;}else{//空闲队列不为空while (after){if (back2->adr == after->adr + after->size){//与前边空闲分区合并before->next = after->next;after->size += back2->size;back2 = after;}else{before = before->next;after = after->next;}}before = head2;after = head2->next;while (after){if (after->adr == back2->adr + back2->size){//与后边空闲区合并before->next = after->next;back2->size += after->size;}else{before = before->next;after = after->next;}}before = head2;after = head2->next;while (!insert){//将被回收的块插入到恰当的位置(按分区大小从小到大)if (after == NULL || ((after->size>back2->size) && (before->size<back2->size))){before->next = back2;back2->next = after;insert = 1;break;}else{before = before->next;after = after->next;}}}if (insert)printf("\t最佳适应算法回收内存成功!\n");elseprintf("\t最佳适应算法回收内存失败!!\n");}void print(char choice)//输出空闲区队列信息{Node *p;if (choice == 'f' || choice == 'F')p = head1->next;elsep = head2->next;if (p){printf("\n空闲区队列的情况为:\n");printf("\t编号\t首址\t终址\t大小\n");while (p){printf("\t%d\t%d\t%d\t%d\n", p->id, p->adr, p->adr + p->size - 1, p->size);p = p->next;}}}void menu()//菜单及主要过程{char chose;int ch, num=0, r, add, rd;while (1){system("cls");printf("-------存储管理动态分区分配及回收算法-------\n");printf(" F 最先适应算法\n");printf(" B 最佳适应算法\n");printf(" E 退出程序\n");printf("----------------------------------------------\n");printf("请选择算法:");cin >> chose;//scanf("%c", &chose);if (chose == 'e' || chose == 'E')exit(0);else{system("cls");while (1){if (chose == 'f' || chose == 'F')printf("最先适应算法:\n");if (chose == 'b' || chose == 'B')printf("最佳适应算法:\n");printf("----------------------------------------------\n");printf(" 1 分配内存\n");printf(" 2 回收内存\n");printf(" 3 查瞧内存\n");printf(" 4 返回\n");printf("----------------------------------------------\n\n");printf("请选择:");scanf("%d", &ch);fflush(stdin);switch (ch){case 1:printf("输入申请的分区大小:"); scanf("%d", &r);if (chose == 'f' || chose == 'F')assign = assignment1(num, r);elseassign = assignment2(num, r);if (assign->adr == -1){printf("分配内存失败!\n");}elseprintf("分配成功!分配的内存的首址为:%d\n", assign->adr);break;case 2:printf("输入释放的内存的首址:"); scanf("%d", &add);printf("输入释放的内存的大小:"); scanf("%d", &r);printf("输入释放的内存的编号:"); scanf("%d", &rd);if (check(add, r, chose)){if (chose == 'f' || chose == 'F')acceptment1(add, r, rd);elseacceptment2(add, r, rd);}break;case 3:print(chose); break;case 4:menu(); break;}}}}}void main()//主函数{init();menu();}四、实验结果操作系统存储管理动态分区分配及回收算法附源码五、实验总结通过这次实验我练习了存储管理动态分区分配及回收算法,对操作系统中动态可变分区存储管理有了更深刻的了解。

相关文档
最新文档