【发布时间】:2014-01-03 01:14:18
【问题描述】:
我必须为我的计算机体系结构课程用 C 语言编写一个缓存模拟器。我对我的要求没有任何问题,我的程序也快完成了,但是我的 CreateCache 方法有问题。出于某种原因,在我创建缓存之后,当我通过索引和标签将单个地址插入缓存时,缓存中的每个集合/块都是相同的。如果我将一个条目添加到 4 组缓存中的第 1 组,则所有 4 组都将具有相同的标签。我的缓存需要能够支持关联(n 路)和直接,并且还必须包括 L1 L2 和 L3 内存。
如果有人可以看看我的方法和结构并告诉我是否有任何明显的错误,我将不胜感激。我已经坚持了好几天了,明天就要交作业了。先谢谢大家了!!
这是我正在使用的结构,以及 createCache 方法。
typedef struct block {
unsigned long tag;
int valid; //0 for invalid, 1 valid
}block;
typedef struct set {
int numBlocks;
block *blks;
int alg;
}set;
typedef struct Cache{
int FIFO, LRU; //index for alg
int hits, misses, reads, writes;
unsigned long accesses;
int cacheSize;
int numSets;
int numBlocks; //total blocks
set *sets;
int blockSize;
int assoc; //number of lines each in set
int alg;
}Cache;
这是我正在使用的 createCache 方法。我认为错误在于我如何使用指针并设置集合和块的数组。
Cache createCache(int cacheSize, int blockSize, int alg, int assoc){
if(cacheSize<=0 || blockSize <=0 || (alg!=0 && alg!=1)){
perror("Invalid input!");
exit;
}
Cache *new = (Cache*)malloc(sizeof(Cache));
//initialize all values
new->hits=0;
new->misses=0;
new->reads=0;
new->writes=0;
new->alg=alg;
new->assoc = assoc;
new->cacheSize=cacheSize;
new->blockSize=blockSize;
new->numBlocks=(int)(cacheSize/blockSize);
new->numSets=(int)(new->numBlocks/assoc);
// new->set->blk = (block*)malloc(sizeof(block)* new->numSets);
//creates array with n sets
if(assoc >= 1){
set *s = malloc(sizeof(set));
block *b = malloc(sizeof(block));
new->sets = s;
new->sets->blks = b;
//for each set
for(int x=0; x < new->numSets; x++){
new->sets[x] = *s;
new->sets[x].alg=alg;
new->sets[x].numBlocks = new->numBlocks;
// new->sets[x] = (set*)malloc(sizeof((set* new->numLines);
for(int y=0; y < assoc; y++){
//add for blks[y]
new->sets[x].blks[y] = *b;
new->sets[x].blks[y].valid = -1;
new->sets[x].blks[y].tag = NULL; //null?
}
}
}//end if
return *new;
}
为了更易于可视化,这就是我打印缓存时发生的情况。在这个例子中,我创建了一个直接缓存并向缓存中添加了一个地址。
Set 0
Block 0
tag 0
Set 1
Block 0
tag 0
Set 2
Block 0
tag 0
Set 3
Block 0
tag 0
Adding address: 7fff006891a8
Set 0
Block 0
tag 7fff006891a
Set 1
Block 0
tag 7fff006891a
Set 2
Block 0
tag 7fff006891a
Set 3
Block 0
tag 7fff006891a
【问题讨论】:
-
在调试器中运行此程序时发现了什么?
-
调试时一切正常,没有错误。但是,当我将地址添加到集合中的单个块中时,由于某种原因,每个集合/块都会分配给它相同的标签。就好像每个额外的集合/块只是指向第一个的指针。我已尽一切努力尝试修复它,但我迷路了。
-
1)
block *b = malloc(sizeof(block));1a)new->sets->blks = b;您在此处分配 1 个块 2)new->sets[x].blks[y] = *b;您在此处将其分配给 assoc 成员。顺便说一句:不要强制转换 malloc() 的返回值 -
问题出在哪里?我不确定我会如何纠正它,因为我已经尝试了我能想到的一切。最终,我需要一个集合数组,每个集合都有一个块数组,等于关联的数量。
-
block *b = malloc(assoc * sizeof *b);
标签: c caching memory simulator allocation