[英]Seg Fault when using malloc for an array of pointers to structs
I'm trying to implement a cache struct with pointers that point to "lower-level" set structs; 我正在尝试使用指向“低级”集合结构的指针来实现缓存结构。 It's supposed to simulate a cache.
应该模拟一个缓存。 When I try to malloc the cache struct in the initCache function I get a seg fault.
当我尝试在initCache函数中分配缓存结构时,出现段错误。 I've read other posts and I'm pretty sure it's not the syntax, but I'm new to C so I could be using the pointers wrong.
我读过其他文章,我很确定这不是语法,但是我是C语言的新手,所以我可能使用了错误的指针。 I get a warning that L1cache may be uninitialized and I've also checked posts related to that but with no luck, trying what worked for others.
我收到一个警告,说L1cache可能尚未初始化,并且我也检查了与此相关的帖子,但是没有运气,尝试对其他人有用的方法。
TO be clear the **sets in the cache definition is supposed to be an array of pointers where each pointer in the array points to a struct 为了清楚起见,缓存定义中的** sets应该是一个指针数组,其中数组中的每个指针都指向一个结构
The cache struct is defined as: 缓存结构定义为:
/* Struct representing the cache */
struct cache{
set **sets; /* Array of set pointers */
};
initCache is called in main as such: initCache在main中这样调用:
cache* L1cache;
initCache(L1cache, nSets, setSize);
The code for initCache is: 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;
}
You need to initialize L1cache
: 您需要初始化
L1cache
:
cache *L1cache = malloc(sizeof (cache));
Or you could just declare it as an ordinary variable: 或者,您可以将其声明为普通变量:
char L1cache;
initCache(&L1cache, nSets, setSize);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.