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];
}
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.