This is my code, which allocates space for a matrix of size specified by the parameters, and returns a pointer to said matrix:
int **allocateSpace(int row, int col){
int i;
int **a;
a = malloc(sizeof(int *) * row);
for(i = 0; i < row; i ++)
a[i] = malloc(sizeof(int) * col);
return a;
}
The above code works as intended.
However, when I change the code to the following form I get a segmentation fault:
void allocateSpace(int **a, int row, int col){
int i;
a = malloc(sizeof(int *) * row);
for(i = 0; i < row; i ++)
a[i] = malloc(sizeof(int) * col);
}
It seems like when returning from the allocateSpace() function, the memory allocated was released (since I got a segmentation fault). But why? All I am doing is allocating memory for a given pointer, and it’s all done in the subfunction.
To summarize my question: Why am I getting a segmentation fault in the second piece of code?
Thank you very much!
Because you need to pass in a pointer to a pointer to a pointer in order to assign the allocated memory:
And to call it you would need to pass the address of an
int**: