2

我在 initializeStruct 函数中遇到分段错误。我想要一个二维数组指针。每个二维数组索引都包含三种类型的结构。

这是结构:

struct cacheLine {
    int validBit;
    int tag;
    int LRUcounter;
};

这是失败的方法:

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;
}

总的来说,我使用 malloc 来创建我的二维数组指针:

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);
4

3 回答 3

2

你做的方式只是malloc'ed你的数组的第一个维度。你需要你的malloc每一行:

struct cacheLine **cacheArray =  malloc(sizeof(struct cacheLine*)*S);
for(i = 0;i < S;i++) {
    cacheLine[i] = malloc(sizeof(struct cacheLine) * E);
}
于 2013-10-11T14:32:44.680 回答
2

您正在声明一个二维数组,即一个指针数组。为此,您分配一个内存区域。

您的期望:

array_0_0, array_0_1, ..., array_0_s
array_1_0, array_1_1, ..., array_1_s
...

您实际声明的内容:

array_0 -> NULL
array_1 -> NULL
...
array_n -> NULL
lots of wasted space

您可以使用带有 malloc 的一维数组,并计算您的索引 (i * E + j),或者您可以坚持使用二维数组,而是单独初始化行。我建议使用一维数组。

于 2013-10-11T14:35:45.660 回答
1

Your malloc is wrong - you want to allocate S in the first malloc then for each of those malloc E items; instead you are malloc'ing S*E and never pointing them at anything

于 2013-10-11T14:32:55.180 回答