reza
reza

Reputation: 13

Segmentation fault,C++,g++,

I have this simple program, when I run this program, I get segmentation fault, I can not recognize where is my mistake. any help welcomed.(segmentation fault for Di>=27). The point is that when I remove function immediately segmentation fault disappears. Or when I transform the function to a void function. I know there is a leak memory because not uses delete operator, it causes leak memory,but easily is not responsible for segmentation fault(This leak memory is very far to produce segmentation fault).for simplicity I didn't use delete operator.

 #include <iostream>
    #include<complex>
    using namespace std;
    const int Di=27;
    typedef struct {
         complex<double> Matrix[Di][Di][Di][Di];

        } O;

    O initializing(int );

    int main()
    {
    O * Operator=new O[1];
    int p;
    int n;
    Operator[0]=initializing(n);
    cout<<"hi";
    return 0;

    }



O initializing(int  point)
{
int i,j,m,n;
O *Operator=new O[1];
for(i=0;i<Di-1;i++)
    for(j=0;j<Di-1;j++)
        for(n=0;n<Di-1;n++)
            for(m=0;m<Di-1;m++)
            Operator[0].Matrix[i][j][m][n]=2;

            cout<<Operator[0].Matrix[Di-1][Di-1][Di-1][Di-1];
return Operator[0];


}

Upvotes: 1

Views: 299

Answers (2)

Mike Seymour
Mike Seymour

Reputation: 254751

I think the problem is that, when returning the object by value, a temporary object might be created on the stack. With Di=27, each object is a few megabytes in size, which is likely to overflow the stack.

You're also allocating (and leaking) at least twice as much memory as you need, by initialising a new object to copy over the existing object.

Better options might be to pass the object to initialise to the function by reference:

void initialise(O & o, int point) {
    for (/*blah blah*/)
        o.Matrix[i][j][m][n]=2;
}

or to give the structure a constructor:

struct O {
    explicit O(int point) {
        for (/*blah blah*/)
            Matrix[i][j][m][n]=2;
    }

    complex<double> Matrix[Di][Di][Di][Di];
};

In any case, do remember to delete anything you allocate with new; or, even better, use a smart pointer to do that for you.

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727087

You are returning a struct with a large array by value, and it does not fit on the stack. Return the struct by pointer, and dereference that pointer in the caller. It would help you avoid a memory leak, too.

O* initializing(int );

int main()
{
    O * Operator=new O[1];
    int p;
    int n;
    O *tmp = initializing(n);
    Operator[0] = *tmp;
    delete[] tmp;
    cout<<"hi";
    return 0;
 }

Upvotes: 3

Related Questions