*** stack detection detected ***: in Gaussian exception

I am writing C ++ code for Gaussian elimination for pedagogical reasons. There are no errors during compilation, but when I run the program I get a stack break error.

Here is what I wrote:

#include <iostream>
#include <stdlib.h>
#include <math.h>

using namespace std;

int main(){
    int i,j,l,n;
    double *c;
    int *indice;
    double a[2][2];

    n=2;
    a[1][1]=1;
    a[1][2]=2;
    a[2][1]=3;
    a[2][2]=4;

    c=new double[n];
    indice=new int[n];
    /*Inizialize indice*/
    for(i=0;i<n;i++){indice[i]=i;}
    /*find scaling factor*/
    for (i=0;i<n;i++){
        double c1=0;
        for (j=0;j<n;j++){
            double c0=abs(a[i][j]);
            if(c0>c1) c1=c0;}
        c[i]=c1;}
    /*find pivot*/
    int k=0;
    for(i=0;i<n-1;i++){
        double pi1=0;
        for(j=i;j<n;j++){
            double pi0=abs(a[indice[j]][i]);
            pi0/=c[indice[j]];
            if(pi0>pi1){
                pi1=pi0;
                k=j;}}
    /*interchange rows according to pivoting order*/
        int itemp=indice[i];
        indice[i]=indice[k];
        indice[k]=itemp;
        for(j=i+1;j<n;j++){
            double pj=a[indice[j]][i]/(a[indice[i]][i]);
    /*recording pivot ratio below diagonal*/
            a[indice[j]][i]=pj;
    /*modify other elements accordingly*/
            for(l=i+1;l<n;l++){
                a[indice[j]][l]-=pj*a[indice[i]][l];}}}

    delete c;
    delete indice;
    return 0;}

what does it mean and where is my mistake?

+3
source share
2 answers

You have an error here:

double a[2][2];

a[1][1]=1;
a[1][2]=2;
a[2][1]=3;
a[2][2]=4;

The range of valid array indices is 0..1, but you are accessing elements with index 2, which is out of scope.

What you might want:

a[0][0]=1;
a[0][1]=2;
a[1][0]=3;
a[1][1]=4;

or more succinctly:

double a[2][2] = { { 1, 2 }, { 3, 4 } };
+5
source

As already noted in another answer, you have indexes that are out of range, for example. in your matrix a:

double a[2][2];

a[1][1]=1;
a[1][2]=2;
a[2][1]=3;
a[2][2]=4;

0 1, 2 ( ++ 0).

, ++ C-. ( operator()(int row, int column)), , , , . , , .

, , .

std::array , C-, at() . ( , std::array operator[] .)


, new[], delete[], delete:

// Your code:
// delete c; 
// delete indice

// Fix:
delete[] c;
delete[] indice;

, , std::vector raw new[]/delete[].

+2

Source: https://habr.com/ru/post/1687567/


All Articles