开发者

large matrix computation

开发者 https://www.devze.com 2023-04-10 22:18 出处:网络
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 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[2开发者_运维问答00][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];
            }
        }
    }
}


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.


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


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)));


stack overflow -> segmentation fault


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号