【问题标题】:Using malloc for 2D array pointer causes segmentation fault将 malloc 用于 2D 数组指针会导致分段错误
【发布时间】:2013-10-11 14:28:50
【问题描述】:

我在 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);

【问题讨论】:

标签: c pointers struct malloc multidimensional-array


【解决方案1】:

你刚才的做法是malloc'ed 数组的第一个维度。 你需要malloc你的每一行:

struct cacheLine **cacheArray =  malloc(sizeof(struct cacheLine*)*S);
for(i = 0;i < S;i++) {
    cacheLine[i] = malloc(sizeof(struct cacheLine) * E);
}

【讨论】:

  • 感谢您的帮助,我将 cacheLine[i] 更改为 cacheArray[i]。再一次,这很棒
【解决方案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),或者您可以坚持使用二维数组,而是单独初始化行。我建议使用一维数组。

【讨论】:

    【解决方案3】:

    您的 malloc 错误 - 您想在第一个 malloc 中分配 S 然后为每个 malloc E 项目分配;相反,您正在 malloc'ing S*E 并且从不将它们指向任何东西

    【讨论】:

    • 谢谢,现在更有意义了。
    • malloc 没有错,他访问它的方式是错误的。
    猜你喜欢
    • 1970-01-01
    • 2021-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-23
    相关资源
    最近更新 更多