[英]Using malloc for 2D array pointer causes segmentation fault
I am getting a segmentation fault in the initializeStruct function. 我在initializeStruct函数中遇到分段错误。 I want a 2D Array pointer. 我想要一个2D数组指针。 Each 2D array index holds a struct of three types. 每个2D数组索引都包含三种类型的结构。
Here is the struct: 这是结构:
struct cacheLine {
int validBit;
int tag;
int LRUcounter;
};
This is the Method that fails: 这是失败的方法:
void initializeStruct(struct cacheLine **anyCache){
int i, j;
for (i=0;i<S;i++){
for(j=0;j<E;j++){
anyCache[i][j].validBit = 0; //I am getting a Segmentation fault
anyCache[i][j].tag = 0;
anyCache[i][j].LRUcounter = 0;
}
}
return;
}
In the main, I use malloc to create my 2D array pointers: 在主要方面,我使用malloc创建2D数组指针:
int main(int argc, char** argv){
int opt;
char *t;
//looping over arguments from command line
while(-1 != (opt = getopt(argc, argv, "s:E:b:t:"))){
//determine which argument it's processing
switch(opt){
case 's':
s = atoi(optarg);
break;
case 'E':
E = atoi(optarg);
break;
case 'b':
b = atoi(optarg);
break;
case 't':
t = optarg;
break;
//too many arguments
default:
printf("wrong argument\n");
break;
}
}
//create array
S = 1 << s;
B = 1 << b;
//allocate memory
struct cacheLine **cacheArray = malloc(sizeof(struct cacheLine)*S*E);
//Initialize Structs
initializeStruct(cacheArray);
The way you did you just malloc
'ed the first dimension of your array. 您刚malloc
的方式是数组的第一维。 You need to malloc
each of your lines: 你需要malloc
每个行:
struct cacheLine **cacheArray = malloc(sizeof(struct cacheLine*)*S);
for(i = 0;i < S;i++) {
cacheLine[i] = malloc(sizeof(struct cacheLine) * E);
}
You are declaring a 2D-array, that is, an array of pointers. 您正在声明一个2D数组,即一个指针数组。 To that you assign a memory area. 为此,您要分配一个存储区。
What you expect: 您的期望:
array_0_0, array_0_1, ..., array_0_s
array_1_0, array_1_1, ..., array_1_s
...
What you actually declared: 您实际声明的内容:
array_0 -> NULL
array_1 -> NULL
...
array_n -> NULL
lots of wasted space
You can either use a 1D array with the malloc, and calculate your indices (i * E + j), or you can stick with the 2d array and instead initialize the lines individually. 您可以将1D数组与malloc一起使用,并计算索引(i * E + j),也可以坚持使用2d数组,然后分别初始化行。 I would suggest using the 1d array. 我建议使用一维数组。
Your malloc is wrong - you want to allocate S
in the first malloc then for each of those malloc E
items; 您的malloc错误-您想在第一个malloc中分配S
,然后再为每个malloc E
项目分配S
; instead you are malloc'ing S*E
and never pointing them at anything 相反,您正在分配S*E
并且永远不要将它们指向任何东西
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.