我有一个用 C 编写缓存模拟的项目,到目前为止,我一直在为数组和程序崩溃分配空间。请帮帮我。我必须在这个程序中使用指针。当我在主函数中简单地创建数组时,没有问题,但是在全局创建指针后,程序开始崩溃,我必须让它全局。它的要求之一。
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <assert.h>
int INDEXLENGTH; // global variable for num of bits in index
int OFFSETLENGTH; // global variable for num of bits in byte offset
int TAGBITS; // global variable for num of bits in the tag
int misses=0; //variable for total number of misses
int hits=0;
int **tagAr; // LRUArray pointer
int **lruAr; // tagArray pointer
int cacheSize; // user specified size of cache
int blockSize; // user specified size of each block
int linesperset;
int sets;
int main(void)
{
int i; // simply a few variables for future for loops
int j;
printf("Welcome to Lab A Cache Simulator by Divya, Alex and Jenn.\n");
printf("To begin, please input the size of the cache you will be simulating in bytes.\n");
scanf(" %d", &cacheSize); // (cache size in bytes) is read in from the user
printf("You have inputed this: %d\n", cacheSize);
printf("Next, please input the size of each cache line in bytes.\n");
scanf(" %d", &blockSize); // blocksize is read in from the user
printf("You have inputed this: %d\n", blockSize);
printf("Finally, please input the number of ways of associativity for this cache.\n");
printf("Also, input the number as a power of 2.\n");
scanf(" %d", &linesperset); // linesperset is read in from the user
printf("You have inputed this: %d\n", linesperset);
sets = (cacheSize/(blockSize*linesperset));
printf("Variable sets is: %d\n", sets);
tagAr=(int **)malloc(sets*sizeof(int *)); // allocating space for "l" array pointers
for (i=0; i<sets; i++) tagAr[i]=(int *)malloc(linesperset*sizeof(int)); //allocates space for k columns for each p[i]
lruAr=(int **)malloc(sets*sizeof(int *)); // allocating space for "l" array pointers
for (i=0; i<sets; i++) lruAr[i]=(int *)malloc(linesperset*sizeof(int)); //allocates space for k columns for each p[i]
for (i=0; i<sets; i++)
{
for (j=0; j<blockSize; j++)
{
tagAr[i][j] = -1;
lruAr[i][j] = -1;
}
}
for (i = 0; i < sets; i++) //This part of the code prints array for debuging purposes
{
for (j = 0; j < blockSize; j++)
{
printf(" %d", lruAr[i][j]);
}
printf("\n");
printf("\n");
}
printf("This is the value of IndexLength before setting, should be 0 : %d\n", INDEXLENGTH); //only for debuging purposes
setIndexLength();
printf("This is the value of IndexLength after setting: %d\n", INDEXLENGTH); //only for debuging purposes
printf("This is the value of OffsetLength before setting, should be 0 : %d\n", OFFSETLENGTH); //only for debuging purposes
offsetLength();
printf("This is the value of OffsetLength after setting: %d\n", OFFSETLENGTH); //only for debuging purposes
return misses;
}