Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question

1 Answer 1

up vote 3 down vote accepted

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)
share|improve this answer
4  
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. –  K Scott Piel Apr 25 '13 at 21:01
    
Wow, I completely missed that! Thank you very much for the second pair of eyes! –  user2321508 Apr 25 '13 at 21:01

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.