简体   繁体   English

将malloc用于2D数组时出现分段错误

[英]Segmentation fault when using malloc for 2D array

I create a 2-D array using malloc . 我使用malloc创建一个二维数组。 When I use printf to print the array element in for loop, everything is fine. 当我使用printf在for循环中打印数组元素时,一切都很好。 But when I want to use printf in main, these is a Segmentation fault: 11. 但是当我要在main中使用printf时,这是一个Segmentation fault: 11.

Could you please tell me what the problem with the following code is? 您能否告诉我以下代码的问题是什么?

#include <stdlib.h>
#include <stdio.h>

void initCache(int **cache, int s, int E){
int i, j;
/* allocate memory to cache */
cache = (int **)malloc(s * sizeof(int *)); //set 
for (i = 0; i < s; i++){
    cache[i] = (int *)malloc(E * sizeof(int)); //int

    for(j = 0; j < E; j++){
        cache[i][j]  = i + j;   
        printf("%d\n", cache[i][j]);
    }
  }
}


main()
{
    int **c;

    initCache (c, 2, 2);

    printf("%d\n", c[1][1]);  // <<<<<<<<<< here

}

Since your cache is a 2D array, it's int** . 由于您的缓存是2D数组,因此它是int** To set it in a function, pass int*** , not int** . 要在函数中设置它,请传递int*** ,而不要传递int** Otherwise, changes to cache made inside initCache have no effect on the value of c from main() . 否则,对initCache内部的cache所做的更改不会影响main()c的值。

void initCache(int ***cache, int s, int E) {
    int i, j;
    /* allocate memory to cache */
    *cache = (int **)malloc(s * sizeof(int *)); //set 
    for (i = 0; i < s; i++) {
        (*cache)[i] = (int *)malloc(E * sizeof(int)); //int
        for(j = 0; j < E; j++){
            (*cache)[i][j]  = i + j;   
            printf("%d\n", (*cache)[i][j]);
        }
    }
}

Now you can call it like this: 现在您可以这样称呼它:

initCache (&c, 2, 2);

You changed a local variable, which won't effect the local variable c in main. 您更改了局部变量,这不会影响main中的局部变量c

If you want to allocate in the function, why pass a variable? 如果要在函数中分配,为什么要传递变量? Return it from the function. 从函数返回它。

int **c = initCache(2, 2);

You could use a return , or else a *** as suggested by others. 您可以使用return ,也可以使用别人建议的*** I'll describe the return method here. 我将在这里描述return方法。

initCache is creating and initializing a suitable array, but it is not returning it. initCache正在创建和初始化合适的数组,但未返回它。 cache is a local variable pointing to the data. cache是指向数据的局部变量。 There are two ways to make this information available to the calling function. 有两种方法可以使此信息可供调用函数使用。 Either return it, or pass in an int*** and use that to record the pointer value. 要么return它,要么传入一个int***并使用它来记录指针值。

I suggest this: 我建议这样:

int** initCache(int **cache, int s, int E){
   ....
   return cache;
}


main()
{
   int **c;
   c = initCache (2, 2);
   printf("%d\n", c[1][1]);   <<<<<<<<<< here
}

==== ====

Finally, it's very important to get in the habit of checking for errors. 最后,养成检查错误的习惯非常重要。 For example, malloc will return NULL if it has run out of memory. 例如,如果malloc内存不足,它将返回NULL Also, you might accidentally as for a negative amount of memory (if s is negative). 另外,您可能会意外地发现内存量为负(如果s为负)。 Therefore I would do: 因此,我会这样做:

cache = (int **)malloc(s * sizeof(int *));
assert(cache);

This will end the program if the malloc fails, and tell you what line has failed. 如果malloc失败,这将结束程序,并告诉您哪一行失败了。 Some people (including me!) would disapprove slightly of using assert like this. 有些人(包括我在内!)会assert喜欢这样使用assert But we'd all agree it's better than having no error checking whatsoever! 但是我们都同意,这比没有任何错误检查要好!

You might need to #include <assert.h> to make this work. 您可能需要#include <assert.h>才能完成此工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM