I am still very new to C programming. The line that I posed below is the one that ends the program. I am not sure why, but I want a dynamic array and I thought this was how I was supposed to allocate the size for it.
Code:
if (cache[block].block == NULL) {
cache[block].block = (int *) malloc(blockSize * sizeof(int));
}
Code:
struct node {
int tag;
int *block; //dynamic array
} *cache = NULL;
typedef struct node n;
int *mm = NULL;
int numLines, blockSize, cacheSize;
void option2()
{
int readOrWrite, mmAddress, writeValue, word, base, set, tag, block;
printf("Enter 0 for read or 1 for write: ");
scanf("%d", &readOrWrite);
if (readOrWrite == 1) {
printf("\nEnter main memory address to write to: ");
scanf("%d", &mmAddress);
printf("\nEnter value to write: ");
scanf("%d", &writeValue);
}
else if (readOrWrite == 0) {
printf("\nEnter main memory address to read from: ");
scanf("%d", &mmAddress);
}
/*calculate tag, line of cache, and word associated w/ MM address */
printf("test1 \n");
tag = mmAddress / cacheSize;
block = 1;
set = (mmAddress % cacheSize) / blockSize;
word = mmAddress % blockSize;
base = (mmAddress / blockSize) * blockSize;
/*3 cases for hit/miss */
//CASE 1: MISS DUE TO UNALLOCATED BLOCK
printf("test2 \n");
if (cache[block].block == NULL) {
cache[block].block = (int *) malloc(blockSize * sizeof(int));
}
//CASE 2: MISS DUE TO NON MATCHING TAGS
printf("test3 \n");
if (cache[block].tag != tag) {
cache[block].tag = tag;
//replace block in the cache
int i;
for (i = 0; i < blockSize; i++) {
cache[block].block[i] = mm[base + 1];
}
if (readOrWrite == 0) {
printf("READ MISS!");
}
else if (readOrWrite == 1) {
printf("WRITE MISS!");
mm[mmAddress] = writeValue;
}
}
//CASE 3: HIT IN THE CACHE, TAGS MATCH
else if (cache[block].tag == tag) {
if (readOrWrite == 0) {
printf("YOU HAVE A READ HIT!");
writeValue = cache[block].block[word];
}
else if (readOrWrite == 1) {
printf("YOU HAVE A WRITE HIT!");
cache[block].block[word] = writeValue;
mm[mmAddress] = writeValue;
}
}
}