简体   繁体   English

使用malloc创建指向指针的数组时出现分段错误

[英]Segmentation fault when using malloc to create array of pointers to pointers

I'm having an issue with dynamically creating a "multi-dimensional array". 我在动态创建“多维数组”时遇到问题。 I've read 6.14 on the comp.lang.c FAQ, and am following the code that was listed there. 我已经阅读了comp.lang.c FAQ上的6.14,并且正在遵循那里列出的代码。

            cache_array = malloc(cm_blks * sizeof(int *));
            if (cache_array = NULL) {
                    fprintf(stderr, "out of memory\n");
                    exit(1);
            }

            for (i = 0; i < cm_blks; i++) {
                    cache_array[i] = malloc(6 * sizeof(int));
                    if (cache_array[i] == NULL) {
                            fprintf(stderr, "out of memory\n");
                            exit(1);

                    }
            }

The variable cm_blks is an integer, in my test case equal to 8. cache_array is initialized as: 在我的测试案例中,变量cm_blks是一个整数,等于8。cache_array初始化为:

    int **cache_array;

The code compiles fine, but I get a segmentation fault at the second malloc line when I run the output. 代码可以正常编译,但是在运行输出时,在第二个malloc行出现了段错误。

This is not an equality check but is an assignment : 这不是一个相等检查,而是一个赋值

if (cache_array = NULL)

which sets cache_array to NULL and does not enter the if branch as the result of the assignment is, essentially, false. 它将cache_array设置为NULL ,并且由于赋值的结果本质上为false,因此不进入if分支。 The code then continues to dereference a NULL pointer. 然后,代码继续取消引用NULL指针。

Change to: 改成:

if (cache_array == NULL)

or: 要么:

if (!cache_array)

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

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