Sayed Omar
Sayed Omar

Reputation: 55

how to get rid of segmentation fault error in c++?

i'm trying to find the determinant of a matrix in c++ and when running the code, a segmentation fault error(core dumped) occurs although i tried to change the code many times but this problem keeps . and here is the code:

#include <iostream>
using namespace std;

const int N = 4;


void get_cofs(int mat[N][N], int temp[N][N], int p, int q, int n){
    int i,j;
    for (int row=0; row<n; row++){
        for (int col=0; col<n; col++){
            if (row != p && col != q){
                temp[i][j++] = mat[row][col];

                if (j == n-1){
                    j = 0;
                    i++;
                }
            }
        }
    }
}


int compute_determinant(int mat[N][N], int n){
    int D =0;
    if (n == 1){
        return mat[0][0];
    }

    int temp[N][N] {0};
    

    int sign =1;
    for (int i = 0; i < n; i++)
    {
        get_cofs(mat,temp,0,i,n);
        D += sign * mat[0][i] * compute_determinant(temp, n-1);

        sign = -sign;
    }
    return D;
}


int main(){
    int mat[4][4] {{1, 0, 2, -1}, 
                     {3, 0, 0, 5}, 
                     {2, 1, 4, -3}, 
                     {1, 0, 5, 0} 
                    }; 
    cout<<compute_determinant(mat, N)<<endl;
    

    return 0;
}

Upvotes: 1

Views: 68

Answers (1)

aspen100
aspen100

Reputation: 965

Like @TrebledJ says, i and j are uninitialized. Using uninitialized variables leads to undefined behaviour. See this for a full treatment.

For your specific case, change int i,j; to int i=0,j=0; and it will stop segfaulting.

Upvotes: 3

Related Questions