Search code examples
c++memory-managementmatrixdeterminants

C++ Matrix Determinant/Memory Allocation


I'm trying to write a matrix determinant function in C++. However my code doesn't compile and don't know why (i'm using an online c++ compîler, and the error messages iget is "* Error in `/var/www/service/usercode/519646917/a.out': free(): invalid next size (fast): 0x00000000019c1180 * " ). It seems that the problem comes from the Free function.

Please can anyone tell me what's wrong in my code?

Thanks in advance Regards

    #include <iostream>
    #include <cmath>
    #include <fstream>
    #include <vector>
    #include <numeric>
    #include <iterator>
    #include <map>
    #include <string>

    //C++ clang

    using namespace std;

    void Free(double** a, unsigned int n)
    {
        if (a!=NULL)
        {
            for (unsigned int j=0 ; j<n ; j++)
            {
                delete[] a[j];
            }
            delete[] a;
        }
    }

    double mDeterminant(double** a, unsigned int n)
    {
    if (n==1)
    {
        return a[0][0];
    }
    else if(n==2)
    {
        return a[0][0]*a[1][1]-a[0][1]*a[1][0];
    }
    else
    {
        double res=0.0;
        for (unsigned int i=0 ; i<n ; i++)
        {


            double** A=new double*[n-1];
            for (unsigned int j=0 ; j<n-1 ; j++)
            {
                A[j]=new double[n-1];
            }

            for (unsigned int j=1 ; j<n ; j++)
            {
                unsigned int g=0;
                for (unsigned int k=0 ; k<n ; k++)
                {
                    if (k!=i)
                    {
                        A[j-1][g]=a[j][k]; g++;
                    }
                }
            }

            res+=a[0][i]*pow(-1, i)*mDeterminant(A, n-1);
            Free(A,n-1);
        }
        return res;
    }

   }

    int main()
    {
        unsigned int N=4;
        double** a=new double*[N];
        for (unsigned int i=0 ; i<N ; i++)
        {
            a[i]=new double[N];
        }

        for (unsigned int i=0 ; i < N ; i++)
        {
            for (unsigned int j=0 ; j < N ; j++)
            {
                a[i][j]=(1+i)*(2+j-i);
                cout << a[i][j] << ";";
            }
            cout << endl;
        }


        cout << "----------------------------------" << endl;
        cout << "mDeterminant = " << mDeterminant(a, N) << endl;

    }

Solution

  • I believe the only error you have (other than the dimensions of array 'a' in main) is with the place where you define g. g should be defined here:

     for (unsigned int j=1 ; j<n ; j++)
     {
          unsigned int g= 0;
          for (unsigned int k=0 ; k<n ; k++)
          {
              if (k!=i)
              {
                  A[j-1][g]=a[j][k]; g++;
              }
          }
      }
    

    Regarding the other n-1 things I understand what you meant with them and I think they are correct