简体   繁体   中英

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.

            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:

    int **cache_array;

The code compiles fine, but I get a segmentation fault at the second malloc line when I run the output.

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. The code then continues to dereference a NULL pointer.

Change to:

if (cache_array == NULL)

or:

if (!cache_array)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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