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
You are only allocating memory for 1
intin each loop iteration. So you have an array of 10 pointers, each pointing tosizeof(int)bytes of memory.only works for arrays of 10 pointers pointing to at least
10*sizeof(int)memory. You should change the line above tocheckMe[i] = malloc(sizeof(int)*10);