Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Dynamic deallocation of a 2D matrix crashing

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading