简体   繁体   中英

what happens to a double pointer when it is passed to a function

Im having some trouble understanding how the pass by value mechanism works in c with pointers. Here is my contrived example...


In my main function, I malloc a pointer to an array of int :

int ** checkMe;
checkMe = malloc(sizeof(int *) * 10);

I understand that this operation sets a side a block of 10 chunks of memory, each block big enough to hold the pointer to an int pointer. I receive back the pointer at the start of this block of 10 chunks.

I have another function that takes that double pointer as an argument:

void test2dArray(int ** arr, int size) {
    int i, j;

    for (i = 0; i < size; i++) {
        // arr[i] = malloc(sizeof(int) * size);
        for (j = 0; j < size; j++) {
            arr[i][j] = i * j;
        }
    }
}

Whenever I leave the commented section as is, and try to malloc the space for the int in main like this:

int ** checkMe;
checkMe = malloc(sizeof(int *) * 10);

for (i = 0; i < 10; i++) {
    checkMe[i] = malloc(sizeof(int));
}

test2dArray(checkMe, 10);

I get memory clobbering whenever I iterate checkMe after the test2dArray call in main .

But if I malloc the space for the int in test2dArray instead (by uncommenting the commented line above) and change my call from main to this:

int ** checkMe;
checkMe = malloc(sizeof(int *) * 10);

test2dArray(checkMe, 10);

the memory clobbering goes away and I can reference checkMe just fine after the function call.


I understand that checkMe is being passed into test2dArray by value. I think this means that the address that is returned by checkMe = malloc(sizeof(int *) * 10); is copied into the function.

I don't understand why the int * 's that checkMe stores gets lost if I don't malloc the space from within test2dArray

When you are allocating in main you are not allocating for 10 integers,

checkMe[i] = malloc(sizeof(int));

change it to

checkMe[i] = malloc(sizeof(int) * 10);
for (i = 0; i < 10; i++) {
    checkMe[i] = malloc(sizeof(int));
}

You are only allocating memory for 1 int in each loop iteration. So you have an array of 10 pointers, each pointing to sizeof(int) bytes of memory.

test2dArray(checkMe, 10);

only works for arrays of 10 pointers pointing to at least 10*sizeof(int) memory. You should change the line above to checkMe[i] = malloc(sizeof(int)*10) ;

Your bug is the difference between this:

checkMe[i] = malloc(sizeof(int));

and this:

arr[i] = malloc(sizeof(int) * size); // size = 10

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