Reputation: 23
Please help me, it reads data from a file.. and uses FIFO replacement algo.. I don't know what's wrong why did the string (when comparing) contains the smiley character when I made sure I put a null terminator..
example file content:
load AAAAAAAA
load AAAAAAAA
load BBBBBBBB
load BBBBBBBB
load BBBBBBBB
load BBBBBBBB
load AAAAAAAA
load CCCCCCCC
load CCCCCCCC
load DDDDDDDD
load EEEEEEEE
load EEEEEEEE
load FFFFFFFF
Try to run it...
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
FILE *fpointer;
typedef struct cache Cache;
struct cache{
char DATA[8];
int COUNT;
int LOAD;
Cache *NEXT;
};
int scan(char *addr, Cache *front){
while(front != NULL){
printf("compare: %s & %s\n", addr, front->DATA);
if(strcmp(addr, front->DATA) == 0){
front->COUNT++;
return 0;
}
front->LOAD++;
front = front->NEXT;
}
return 1;
}
void FirstInFirstOut(int x){
Cache *ITEM[x];
Cache *front, *head;
Cache *node;
char addr[8]="";
int i=0, j=0, k=0, m=0;
for(i=0; i<x; i++){
ITEM[i] = NULL;
}
front = NULL;
head = NULL;
while(!feof(fpointer)){
fscanf(fpointer, "load %c%c%c%c%c%c%c%c\n", &addr[0],&addr[1],&addr[2],&addr[3],&addr[4],&addr[5],&addr[6],&addr[7]);
addr[8] = '\0';
printf("read item: %s\n", addr);
if(front != NULL){
if(scan(addr, front)==0)
continue;
}
node = (Cache*)malloc(sizeof(Cache));
strcpy(node->DATA, addr);
node->COUNT = 0;
node->LOAD = 0;
node->NEXT = NULL;
if(head == NULL){
head = node;
front = node;
}else{
head->NEXT = node;
head = node;
}
if(j<x){
ITEM[j] = node;
printf("insert... %s\n", ITEM[j]->DATA);
}else{
m = j%x; //get the new index
free(ITEM[m]);
ITEM[m] = node;
printf("insert... %s\n", ITEM[m]->DATA);
}
j++;
}
printf("Cache itmes:\n");
for(i=0; i<x; i++){
printf("Item %d: ", i+1);
if(ITEM[i]->DATA == NULL){
printf("NULL\n");
}else{
for(k=0; k<8; k++){
printf("%c", ITEM[i]->DATA[k]);
}
printf("\n");
}
free(ITEM[i]);
}
}
int main(){
char fname[20]="", algo[5]="";
int entries=0;
printf("Input file:\n");
scanf("%s", fname);
printf("Number of cache items:\n");
scanf("%d", &entries);
printf("Replacement algorithm:\n");
scanf("%s", algo);
if((fpointer = fopen(fname,"r")) == NULL){
printf("Error opening file.\n");
return main();
}
if(entries == 0){
printf("Nothing in the cache.\n");
return main();
}
if(strcmp(algo, "FIFO") == 0){
FirstInFirstOut(entries);
}
return main();
}
Upvotes: 2
Views: 1962
Reputation: 455440
One problem I can see is:
char addr[8]="";
....
addr[8] = '\0';
which is incorrect. Since index in C are 0
based, 8
is not a valid index.
Looks like you want a char array to hold 8
characters(apart from the NUL char). In that case you will have to declare it to have size 9
Also looks like you are copying this string addr
into structure member DATA
. So you'll have to change the size of DATA
char array from 8
to 9
aswell.
Upvotes: 7