0

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.

1 Answer 1

3

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Good catch. It looks odd to many people, but it's often a good idea to place constants ahead of variables in conditional tests... for example: if( NULL = cache_array ) would have caught the error as an attempt to assign a variable to a constant. It's a handy way to avoid these kind of subtle errors.
Wow, I completely missed that! Thank you very much for the second pair of eyes!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.