Home > Mobile >  Segmentation Fault in Matrix Inverse
Segmentation Fault in Matrix Inverse

Time:10-26

I am trying to calculate the inverse of a matrix but I get a segmentation fault error in my code but I am not sure where and why this occurs.

This is my code:

double** inverse(double *mat[], int n){
    //identity matrix
    double **I = malloc(sizeof(double*) * n);
        for (int i=0; i<n; i  ) I[i] = malloc(sizeof(double) * n);
        for(int i=0; i<n; i  ){
            for(int j=0; j<n; j  ){
                if(i==j){
                    I[i][j] = 1;
                }else{
                    I[i][j] = 0;
                }
            }
        }
    
    //works until here
        
        double f = 0.0;
        double sub = 0.0;
        for(int p=0; p<n; n  ){
            f = mat[p][p];
            for(int x=0; x<n; x  ){
                mat[p][x] = mat[p][x] / f;
                I[p][x] = I[p][x] / f;
            } 
            for(int i=p 1; i<n; i  ){
                f = mat[i][p];
                for(int x=0; x<n; x  ){
                    sub = mat[p][x] * f;
                    mat[i][x] = mat[i][x] - sub;
                    
                    sub = I[p][x] * f;
                    I[i][x] = I[i][x] - sub;
                }
            }
        }
        
        for(int p=n-1; p>=0; p--){
            for(int i=p-1; i>=0; i--){
                f = mat[i][p];
                for(int x=0; x<n; x  ){
                    sub = mat[p][x] * f;
                    mat[i][x] = mat[i][x] - sub;
                    
                    sub = I[p][x] * f;
                    I[i][x] = I[i][x] - sub;
                }
            }
        }
        
        //return I;
            printf("I:\n");
        for(int i=0; i<n; i  ){
            for(int j=0; j<n; j  ){
                printf("%f ",I[i][j]);
            }
            printf("\n");
        }
        
        //free
        for (int i=0; i<n; i  ) free(I[i]);
        free(I);
}

The matrix I pass in is a nxn matrix with values in every row and column. The code seems to work until I reach the first for loop, I do not know why I am getting this error because the loop stays in bounds of the matrices.

CodePudding user response:

Your error seems to be a small typo right in this for-loop!

for(int p=0; p<n; n  )

You are incrementing n on each iteration, not p so you end up accessing memory you don't own.

  • Related