peaceman
peaceman

Reputation: 1529

large matrix computation

I write a simple code in C++ and I compile it with g++ on linux ubuntu 11.04 and I don't get any errors but when I run the executable file, I get this error "segmentation fault".

I know that my code has no problem and tHat this error is related to the compiler.

Can somebody help me?

My code is :

#include <math.h>
int main()
{
    double a[200][200][200],b[200][200][200],c[200][200][200];
    int i,j,k;

    double const pi=3.14;

    for(k=0;k<200;k++)
    {
        for(j=0;j<200;j++)
        {
            for(i=0;i<200;i++)
            {
                a[i][j][k]=sin(1.5*pi*i)*cos(3.5*pi*j)*k;
                b[i][j][k]=cos(1.5*pi*i)*cos(2.5*pi*k)*j;
                c[i][j][k]=a[i][j][k]-b[i][j][k];
            }
        }
    }
}

Upvotes: 5

Views: 644

Answers (5)

user1432332
user1432332

Reputation:

This function can help you:

double ***alloc3d(int l, int m, int n) {
    double *data = new double [l*m*n];
    double ***array = new double **[l];
    for (int i=0; i<l; i++) {
        array[i] = new double *[m];
        for (int j=0; j<m; j++) {
            array[i][j] = &(data[(i*m+j)*n]);
        }
    }

    return array;
}

Upvotes: 2

peaceman
peaceman

Reputation: 1529

for a non symmetric case we must use this:

    double*** a=new double**[IE];
    for(int i=0;i<IE;i++){
        a[i]=new double *[JE];
        for(int j=0;j<JE;j++){
            a[i][j]=new double [KE];
        }
    }

with above code we can build huge matrixes as our computer's ram allows.

Upvotes: 1

a-z
a-z

Reputation: 1664

stack overflow -> segmentation fault

Upvotes: 1

Mark B
Mark B

Reputation: 96243

You're putting huge arrays of double onto the stack (presumably, assuming that's how your architecture does local variables). Almost surely your system's stack can't hold that much space.

Instead, use vectors instead to allocate on the heap:

std::vector<std::vector<std::vector<double> > > a(200, std::vector<std::vector<double> >(200, std::vector<double>(200)));

Upvotes: 2

NPE
NPE

Reputation: 500247

The three arrays require about 190MB of space, which almost certainly exceeds the stack size limit imposed by your operating system.

Try allocating them on the heap (using new) instead of placing them on the stack.

Upvotes: 13

Related Questions