Home > Software design >  Dynamic deallocation of a 2D matrix crashing
Dynamic deallocation of a 2D matrix crashing

Time:01-11

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

CodePudding user response:

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.

CodePudding user response:

You do not create 2D array only an array of pointers. Make your life easier and locate a real 2D array. Also, use the correct type for sizes size_t

void CreatMat(size_t N, int (**array)[N])
{
    *array = malloc(N * sizeof(**array));
}

int main(void)
{
    int (*array)[N];
    CreatMat(1000, &array);

    /* some code */

    free(array);
}

See how much easier it is.

  •  Tags:  
  • Related