使用malloc作为指向结构的指针数组时出现Seg错误

时间:2014-12-14 11:24:35

标签: c malloc

我正在尝试使用指向“低级”集结构的指针来实现缓存结构;它应该模拟缓存。当我尝试在initCache函数中malloc缓存结构时,我得到一个seg错误。我已经阅读了其他帖子,我很确定这不是语法,但我是C的新手,所以我可能会错误地使用指针。我得到一个警告,L1cache可能没有初始化,我也检查过与此相关的帖子,但没有运气,尝试对其他人有效。

要清楚缓存定义中的**集应该是一个指针数组,其中数组中的每个指针都指向一个结构

缓存结构定义为:

/* Struct representing the cache */
struct cache{
    set **sets; /* Array of set pointers */
};

在main中调用initCache:

cache* L1cache;
initCache(L1cache, nSets, setSize);

initCache的代码是:

void initCache(cache* c, int nSets, int setSize){
    int i;

    c->sets=malloc(nSets*sizeof(set*)); /* SEG FAULT HERE malloc space for array of pointers to each set       */

    for(i = 0; i < nSets; i++){
        c->sets[i]=malloc(sizeof(set)); /* malloc space for each set */
    initSet(c->sets[i],setSize);
}

    return;     
}

1 个答案:

答案 0 :(得分:2)

您需要初始化L1cache

cache *L1cache = malloc(sizeof (cache));

或者您可以将其声明为普通变量:

char L1cache;
initCache(&L1cache, nSets, setSize);