自从我写 C 以来已经有一段时间了,所以这个错误让我觉得我疯了。我正在编写一个程序来模拟一个简单的缓存。不要担心细节。
问题是当我初始化缓存时。在 SA_cacheInit 的行中:
cur_lru = cache->sets + i;//[i];
使用括号失败,并且在 GDB 中检查时,即使 i = 0,它最终也会给出一个空指针。但是,如果我只使用普通的指针算术,它就可以工作。我究竟做错了什么?
typedef struct s_LRUnode {
int tag;
bool valid;
bool dirty;
struct s_LRUnode *next;
struct s_LRUnode *prev;
} LRUnode;
typedef struct s_LRU {
size_t size;
LRUnode *head;
LRUnode *tail;
} LRU;
typedef struct s_SA_cache {
size_t blocksize;
size_t num_blocks;
size_t set_size;
LRU **sets;
} SA_cache;
void cachesim_init(int blocksize, int cachesize, int ways) {
cache = malloc(sizeof(SA_cache));
if ( cache != NULL ) {
assert( powerOfTwo(cachesize) && powerOfTwo(blocksize) );
cache->num_blocks = cachesize / blocksize;
cache->blocksize = blocksize;
cache->set_size = ways;
cache->sets = malloc(sizeof(LRU)*cache->num_blocks); //cache->num_blocks*ways);
if (cache->sets == NULL) {
printf(stderr, "Malloc failed in %s\n", func);
}
SA_cacheInit(cache, cache->num_blocks, ways);
} else {
fprintf(stderr, "Could not allocate memory for cache\n");
exit(-1);
}
}
void SA_cacheInit(SA_cache *cache, size_t num_blocks, size_t size) {
int i;
LRU *cur_lru;
for (i = 0; i < num_blocks; i++) {
cur_lru = cache->sets + i;//[i];
cur_lru->size = size;
cur_lru->head = NULL;
cur_lru->tail = NULL;
}
}