Итак, у меня есть домашняя работа, которая использует программу c для чтения адреса из текстового документа и для проверки того, что он попал или промахнулся. Когда я делаю окончательный процесс для печати индекса и значения, номер мусора происходит, но я не знаю, почему всегда печатать что-то вроде этого:Массив структурной печати и модификации
printinfo index loop: 8
printinfo index loop: 779318117
что, безусловно, неправильно, поскольку индекс должен быть 0-7, а не 8 или этот обалденный номер
Вот код:
/*
*This is the program for lab assignment3 the Cache Simulator
*
* Format of cache:
* Since the cache block size is 4 words,
* 4 words = 4 *4bytes = 16 bytes
* So the offset will be 4 bits (0-3)
* We know the cache have 8 entries
* 2 ^3 = 8
* So the index will be 3 bits (4-6)
* Since this is a 32 bit address
* Tag = 31 - 4 - 3 = 31-7 = 24 bits (7-30)
* The format of each cache line will be:
* 31-8 5-7 1-4 0
* | Tag | |index| |offset| |valid|
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define BLOCK_SIZE 16 // each block store 4 words
#define FILE_NAME "address.txt"
#define NUMBER_OF_ADDRESS 10
#define OFFSET_BIT 4
#define INDEX_BIT 3
struct Cache_file
{
int tag;
int valid;
unsigned int index;
int dataLow;
};
//function prototypes
void printState (struct Cache_file cacheLine[] , int totalCacheLineNum);
void readFile(FILE *filePtr, char* inFileName, int accessTime,
int *address, struct Cache_file cacheLine[]);
void checkHit(int address[], struct Cache_file cacheLine[], int accessTime);
void printHeader();
void printInfo(int hitNum, int missNum, float hitRate, float missRate, int totalAccess, struct Cache_file cacheLine[]);
//functions to print miss rate and hit rate
void printInfo(int hitNum, int missNum, float hitRate, float missRate,int totalAccess, struct Cache_file cacheLine[])
{
printf("The total hit time is: %d\n", hitNum);
printf("The total miss time is: %d\n", missNum);
printf("The hit rate is: %0.3f\n", hitRate);
printf("The miss rate is: %0.3f\n", missRate);
printHeader();
int i=0;
for(i;i<totalAccess; i++)
{
printf("printinfo index loop: %d\n", cacheLine[i].index);
}
}
// the header
void printHeader()
{
printf("<Cache State>: \n");
printf("Index Tag Valid\t Data\n");
printf("-------------------------------------------------------\n");
}
void checkHit(int *address, struct Cache_file cacheLine[], int accessTime)
{
//test
int j =0;
for(j;j<accessTime;j++)
{
printf("the address in checkHit: %.6lX\n" ,address[j]);
}
int missNum = 0;
int hitNum = 0;
float hitRate = 0.0;
float missRate = 0.0;
// tag = address/2^(offset+index bits)
int exp = OFFSET_BIT+INDEX_BIT;
int dn = pow(2,exp);
int indx = 0;
int tag = 0;
int i=0;
for(i;i<accessTime;i++)
{
indx = (address[i]/BLOCK_SIZE)%8; //0-7
printf("index in checkHit loop: %d\n", indx);
// printf("index cacheline[%d]: %d \n",i,cacheLine[i].index);
tag= (address[i] /dn);
if(cacheLine[indx].valid ==0)
{
printf("IF cacheline index in if, i=%d, index=%d\n", i, cacheLine[indx].index);
missNum++;
cacheLine[indx].valid = 1;
}
else
{
if(cacheLine[indx].tag == tag)
{
hitNum++;
}
else
{
missNum++;
}
printf("ELSE cacheline index in else, i=%d, index=%d\n", i, cacheLine[indx].index);
}
cacheLine[indx].tag = tag;
cacheLine[indx].dataLow = (address[i]/16)*16;
}
int as=0;
for(as;as<8;as++)
{
printf("after loop cache[%d] index: %lx\n", as,cacheLine[as].index);
}
int numberOfCacheLines = 8;
hitRate = (float)hitNum/(float)accessTime;
missRate = (float)missNum/(float)accessTime;
printInfo(hitNum, missNum, hitRate, missRate,numberOfCacheLines,cacheLine);
}
//the function to read address from file and store them into array
void readFile(FILE *filePtr, char* inFileName, int accessTime,
int *address, struct Cache_file cacheLine[])
{
//open the file
filePtr = fopen(inFileName , "r");
// start reading the address
int i=0;
for(i;i<NUMBER_OF_ADDRESS ;i++)
{
fscanf(filePtr, "%lX", &address[i]);
}
i = 0;
for(i;i<NUMBER_OF_ADDRESS;i++)
{
printf("address divided by 16 mod 8: %d\n", (address[i]/BLOCK_SIZE)%8);
}
// default the value in every cache line
i = 0;
for(i;i<8;i++)
{
cacheLine[i].tag = 0;
cacheLine[i].index = i;
cacheLine[i].valid = 0;
cacheLine[i].dataLow = 0;
printf("initialized index: %d\n", cacheLine[i].index);
}
//test
i = 0;
for(i;i<accessTime;i++)
{
printf("address in array in read: %0.6lX\n", address[i]);
}
// pass the cache line and address array in to calculation
checkHit(address, &cacheLine, accessTime);
fclose(filePtr);
}
int main()
{
// the total time to access
// default value is Number of access;
int accessTime = NUMBER_OF_ADDRESS;
// declare the address array
int address[NUMBER_OF_ADDRESS];
//store into each structure of cache line array cacheLine[NUMBER_OF_ADDRESS]
// index = (address/cache block size) % 8
// = (address/ 16 bytes) %8
// so the range of index will be 0-7
// declare a array of cache line index form 0-8
struct Cache_file cacheLine[8];
//declare the file pointer and file name
char inFileName[] = FILE_NAME;
FILE *ptr;
// start the simulator by reading the file
// put the reading address into address array
// pass the cache line array to start the simulation
readFile(ptr,inFileName,accessTime,&address,&cacheLine);
return 0;
}
Первые десять адресов в текстовом документе здесь:
0x00000033
0x00000003
0x00000003
0x00000003
0x00000003
0x0000005A
0x0000000B
0x00000000
0x00000009
0x0000000A
Вы активировали свой любимый отладчик и отслеживали его программу? В конечном итоге вы узнаете больше, если научитесь отлаживать свои собственные ошибки, а не обращаться к помощи. – kaylum
Вы уверены, что инициализировали свой массив? – stackptr
Я включил отладчик, но проблема сначала возникла в операторе if/esle, но я не нашел, что не так с оператором – WhiteJade