【发布时间】:2012-11-10 00:50:15
【问题描述】:
我已经有一段时间没有写 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;
}
}
【问题讨论】:
标签: c malloc dynamic-memory-allocation square-bracket