what's the error in this code? the program runs but the output seem to have incorrect result.
#include <stdio.h>
int main() {
int frameno, pageno, pHits = 0, pFaults = 0;
printf("\nEnter Page Frame: ");
scanf("%d", &frameno);
printf("\nEnter Pages: ");
scanf("%d", &pageno);
printf("Enter string: ");
int p, n, i;
char temp[frameno], pageref[pageno];
for (p = 0; p < pageno; p++) {
scanf(" %c", &pageref[p]);
}
printf("\nPage Requested \t ");
for (n = 0; n < frameno; n++) {
printf("Page Frame %d \t", n + 1);
temp[n] = '-'; // Initialize with a character that doesn't conflict with pages
}
for (p = 0; p < pageno; p++) {
int pageFound = 0;
for (i = 0; i < frameno; i++) {
if (pageref[p] == temp[i]) {
pHits++;
pageFound = 1;
break;
}
}
pFaults++;
if (!pageFound) {
if (pFaults <= frameno && pHits == 0) {
temp[p] = pageref[p];
} else {
temp[(pFaults - 1) % frameno] = pageref[p];
}
}
printf("\n%c\t", pageref[p]);
for (i = 0; i < frameno; i++) {
if (temp[i] != '-') {
printf("\t\t %c", temp[i]);
} else {
printf(" \t\t");
}
}
}
printf("\nPage Faults: %d\t", pFaults);
printf("\nPage Hits: %d\t", pHits);
return 0;
}
The ouput came out like this, there should be 5 in page frame 1.
Enter Page Frame: 3
Enter Pages: 5
Enter string: 41245
FIFO
Page Requested Page Frame 1 Page Frame 2 Page Frame 3
4 4
1 4 1
2 4 1 2
4 4 1 2
5 4 1 2
Page Faults: 5
Page Hits: 1
I'm assuming that you want to evict the oldest page, the one that came in "first". Not necessarily what is in frame[0], although frame[0] would be the first frame to be ejected since it would contain the first insert. If you only evicted from frame[0], then frames[1] and frames[2] would never change after having something loaded in them.
We'll introduce one additional array:
Which represents the "time" each page was inserted into your
temparray. And then we'll introduce a clock, which is just an integer that increases by 1 each time there's a page fault. You could also just use your pPageFaults counter as well for the time since it's also monotonically increasing.When we have a page fault, we'll use
insertTimesto find the frame with the oldest entry in it by finding the smallest value in it and using the index found to be the indicator of "frame with oldest page"Also, while we're at it, we'll fix the bug in your code that was also increment pPageFaults by 1 regardless of whether there was one or not.
For your consideration:
Sample run: