I am trying to do page replacement algorithm in C. I wrote the code below. I have written similar code that had worked below. But now when I try to reproduce the code enters an infinite loop.
I checked the for loop for hit and miss and it becomes stationary while current increments are unlimited. I have been tweaking the program for some time but nothing seems to work.
#include<stdio.h>
#include<stdlib.h>
int n,table[20],fsize,i,j,request[20],arr2[20],current,miss;
void initialize(int arr[],int n){ //set frame entries to -1
for(i=0;i<n;i++){
arr[i]=-1;
}
}
int isavailable(int arg){ //checks if entry is available in frame table (array)
int present=0;
for(i=0;i<fsize;i++){
if(table[i]==arg){
present=1;
break;
}
}
return present;
}
void fifo(){ //first in first out
miss=0;
current=-1;
initialize(table,fsize);
for(i=0;i<n;i++){
arr2[i]=request[i];
}
for(i=0;i<n;i++){
if(isavailable(arr2[i])==1){ //hit condition
printf("Hit");
continue;
}
current=(current+1)%fsize; //interates in a cycle during miss
table[current]=arr2[i]; //places in first entered location
miss++;
}
printf("Total misses: %d",miss);
}
void main(){
printf("Enter number of requests: ");
scanf("%d",&n);
printf("Enter table size: "); //reads frame table size
scanf("%d",&fsize);
printf("Enter requests: ");
for(i=0;i<n;i++){
scanf("%d",&request[i]); //reads request sequence in array
}
printf("FIFO: ");
fifo();
printf("LRU: ");
//lru();
printf("Optimal: ");
//optimal();
}
Edit:- The input i gave are:-
- no of requests: 7
- sizeoftable: 3
- request: 1,3,0,3,5,6,3
An input of
will cause
scanf("%d",&request[i]);to fail on the second iteration when it reads an invalid character of,. This character will be left in the input buffer, and will cause subsequent iterations to also fail.Only the first element of
requestis given a user-submitted value, the rest remain zero-initialized (due to static allocation).You must check the return value of
scanfis the expected number of conversions. Here we want to convert one integer (%d), so we check for a return value of1(or the inverse to check for error).%dskips leading whitespace, so the inputis more appropriate for the specifier.
Using the global variable
ias a for the loop condition in bothfifoand the nested call toisavailablecauses the value to ping-pong between1and0(with the given input), thus never reachingn.The solution is to use more locally scoped variables, so that functions do not interfere with each other.
Here is a refactored example.