您的位置:首页 > 其它

动态内存分配c++实现的一个难题!!!请高手帮忙!

2007-07-15 00:08 288 查看
最进在用c++实现动态内存分配模拟程序,基于最坏适应算法wf,

但是内存分配函数中的一个for循环不知怎地就是不正确。代码如下:

 #include <iostream.h>
#include <string.h>
#include <stdlib.h>
#include <malloc.h>
#include <stdio.h>
struct  block{
 char name[10];//块名称
    int address;//起始地址
 int state;//块标志,,0空闲,1占用
 int size;//块大小,即作业大小
 struct  block *next;//指向后继节点
 struct  block *front;//指向前驱节点
};
struct  block *head;//空闲表头执针
struct  block *ahead;//分配表头指针
//初始化内存函数
void initial(){
     head=new block;
  cout<<"主存大小为100k"<<endl;
  cout<<"系统初始化中......"<<endl;
  head->size=100;
  head->address=0;
  head->state=0;
 
  ahead=new block;
  strcpy(ahead->name,"sysa");
  ahead->address=30;
  ahead->size=10;
  ahead->state=1;
  block *p1=new block;
  strcpy(p1->name,"sysb");
  p1->address=60;
  p1->size=20;
  p1->state=1;
  block *p2=new block;
  strcpy(p2->name,"sysc");
  p2->address=90;
  p2->size=5;
  p2->state=1;

  head->size=30;
  block *p3=new block;
  p3->address=40;
  p3->size=20;
  p3->state=0;
  block *p4=new block;
  p4->address=80;
  p4->size=10;
  p4->state=0;
  block *p5=new block;
  p5->address=95;
  p5->size=5;
  p5->state=0;

  head->front=NULL;
  head->next=p3;
  p3->front=head;
  p3->next=p4;
  p4->front=p3;
  p4->next=p5;
  p5->front=p4;
  p5->next=NULL;

  ahead->front=NULL;
  ahead->next=p1;
  p1->front=ahead;
  p1->next=p2;
  p2->front=p1;
  p2->next=NULL;
}

//分配内存函数
void alloc(){
 block *s;
 char str[10];
 int n;

 cout<<"input the job name and size:"<<endl;
 cin>>str;
 cin>>n;
  if(n>head->size){
      cout<<"内存不足分配失败,稍后再试"<<endl;
         return;}
 else if(n==head->size){
  
  head->state=1;
  strcpy(head->name,str);
  s=head;
  head=head->next;
  head->front=NULL;
  s->next=NULL;

  s->next=ahead->next;
  ahead->next->front=s;
  ahead->next=s;
  s->front=ahead;//头指针后面插入
 }
 else{
  

  block *p=new block;
  strcpy(p->name,str);
  p->size=n;
  p->address=(head->address+head->size-n);
  p->state=1;
  p->front=NULL;
  p->next=NULL;

   p->next=ahead->next;
  ahead->next->front=p;
  ahead->next=p;
  p->front=ahead;
 
  block *ss=new block;
  ss=head;
  head->size-=n;
  
  if(ss->size<head->next->size){
  head=head->next;
   head->front=NULL;
   
   ss->next=NULL;
   block *l=new block;//以下是不正确地方
   for(l=head;ss->size<=l->size;l=l->next);//从已经从大到小排序的双向链表中将头指针中的剩余空闲快插入到合适的地方,这个for循环和下面的插入操作错在哪里啊???

    //链表插入操作

ss->next=l->next;l->next->front=ss;
    l->next=ss;
    s->front=l;
    
     
 }
}
bugger调试说unhandled exception    c0000005 vilation access 字样

不能完成插入操作!!!!!!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息