I have a function which allocates 2D matrix at the start and a function which deallocates it, which I use at the end.
int** CreatMat(int N){
int i,**T;
T = (int**)malloc(sizeof(int*)*N);
if(T!=NULL){
for(i=0;i<N;i++){
T[i]=(int*)malloc(sizeof(int)*N);
if(T[i]==NULL){
printf("\nCreatMat()::Allocation failed at block %d",i);
for(i=i;i>=0;i--){
free(T[i]);
T[i]=NULL;
}
free(T);
T=NULL;
return T;
}
}
}
return T;
}
//Free a dynamic matrix.
void FreeMat(int** T,int N){
int i;
for(i=0;i<N;i++){
free(T[i]);
T[i]=NULL;
}
free(T);
T = NULL;
}
Somehow, FreeMat() is crashing. any help?
Full code here
>Solution :
In function main() this
int **T, **S;
if(Grids_Init(T, S) != 0)
does not affect the value of the local variables S and T which remain uninitialised, and you then go on to free these indeterminate pointers.
You can use a function to initialise one of them, return the pointer and assign it to T. Then same for S.
This is preferable to using the three-star pointers: please see Triple pointers in C: is it a matter of style? One answer begins with
Using triple pointers is harming both readability and maintainability.