死亡岛全流程解说:内存页面置换算法代码

来源:百度文库 编辑:高校问答 时间:2024/05/06 06:18:30
这段代码那里错了?怎么改?望高手指教
有加分 在线等答复

#include "stdafx.h"
#include<stdio.h>
#include<conio.h>
#include <malloc.h>
#define N 20

typedef struct page

{

int num; /*记录页面号*/

int time; /*记录调入内存时间*/

struct page * next;

}Page; /* 页面逻辑结构,结构为方便算法实现设计*/

int queue[100]; /*记录调入队列*/

int K; /*调入队列计数变量*/

int l;

Page * head;

void insert(Page * i,Page * top)

{

if (top==NULL)
top=i;

else
while (top->next!=NULL)
top=top->next;
top->next=i;
top=head;

}

/*初始化内存单元、缓冲区*/

void Init()

{

int i;

Page * node;

head=NULL;

for(i=0;i<l;i++)

{ node=(Page *)malloc(sizeof(Page));

node->num=-1;

node->time=l-i-1;

node->next=NULL;

insert(node,head);

}

}

Page * Equation(int fold,Page *b)

{ while (b!=NULL)

{ if (b->num==fold)
return b;
else
b=b->next;
}

return b;
}

Page * GetMax(Page *b)

{

int max=-1;

Page * tag;

while (b!=NULL)
{ if (b->time>max)
{ max=b->time;
tag=b;
}

b=b->next;
}
return tag;
}

void Lru(int fold,Page * b)
{

Page * val;

val=Equation(fold,b);
if (val)
{ val->time=0;

while(b!=NULL)
{ if (b->num==fold)
b->time=0;
else
b->time++;
b=b->next;

}

}

else
{ queue[K++]=fold;/*记录调入页面*/
val=GetMax(head);
val->num=fold;
val->time=0;
while (b!=NULL)
{ if (b->num!=fold)
b->time++;
b=b->next;
}

}

}

int main(int argc, char* argv[])
{
int a[N];

int i;

start: printf("请输入页面序列:");

for (i=0;i<N;i++)
scanf("%d",&a[i]);

printf("请输入分配页面数:");

scanf("%d",&l);

K=0;

Init();

for (i=0;i<N;i++)
Lru(a[i],head);

printf("\n缺页次数为:%6d\n缺页率:%16.6f",K,(float)(K)/N);
printf("\nAre you continuing!\ty?");

if(getche()=='y')

goto start;

return 1;
}

没有仔细看,但发现了一个很容易发生的错误,即函数参数的传递问题。
Init()的最后一句insert(node,head),因为C语言里函数参数采用值传递,那么insert函数执行前head为NULL,执行时,程序会生成一个临时的值为NULL的指针变量作为参数来处理,函数执行完后,head仍为NULL,没有任何改变。因此,就算循环执行了20次,head仍为NULL.