Search code examples
arrayscmallocdereference

C Indexing into double pointer to array causes crash


I have the following simplified code to allocate space for and assign values to an array from another function, passed in by a pointer to the array. A crash is caused when indexing into the dereferenced pointer:

void foo(int **arr) {
    int num_elements = 3;
    *arr = malloc(num_elements*sizeof(int));

    for(int i=0; i<num_elements; i++){
        *arr[i] = i;  // crashes here
    }
}

int main(){
    int *main_arr = NULL;

    foo(&main_arr);

    // Doesn't get here
    for(int i=0; i<3; i++)
        printf("%d ", main_arr[i]);

    printf("\n");
    return 0;
}

I'm expecting the output 0 1 2 , but instead I see Segmentation fault (core dumped). The logic of what I'm doing seems sound, so I don't know what to do about it.


Solution

  • The problem turned out to be an ambiguity: while the logic of the code was sound, on the line that was crashing I interpreted to mean "dereference, then access the ith element", but the compiler evidently interpreted to mean "access the ith element, then dereference". Indeed, using parenthesis to explicitly state my intent solved the problem: Changing to

        for(int i=0; i<num_elements; i++)
            (*arr)[i] = i
    

    produces the desired 0 1 2 output. Turns out that syntax is important!

    Edit: As @JonathanLeffler pointed out, "ambiguous" was a poor word choice, as it's defined behavior that * has a lower precedence than []