简体   繁体   中英

Why do i get a segmentation fault (core dumped) in the program below when i use N=1023 instead of 1024?

Below is a simple program to plot a 2D gaussian, for N=1022 and below the program works fine, but for N=1023 and higher i get Segmentation error(core dumped), am i missing something?

I have not used pointers anywhere, except for writing the data file

#include<stdio.h>
#include<math.h>

void main()
{
    int i, j;
    int N;
    N=1022;
    //Why will i get a segmentation fault if i use 1023 instead of 1024?
    double M[N][N];
    double x[N];
    double y[N];
    double xmax,ymax;
    double dx,dy;
    FILE *fp1,*fp2;
    fp2=fopen("strtfn.txt","w+");

    xmax=10;
    dx=(2*xmax)/N;
    for(i=0; i<N; i++)
    {
        x[i]=-xmax+(i*dx);
    }
    ymax=10;
    dy=(2*ymax)/N;
    for(i=0; i<N; i++)
    {
        y[i]=-ymax+(i*dy);
    }

    for(i=0;i<N;i++)
    {
        for(j=0;j<N;j++)
        {
            M[i][j]=exp(-x[i]*x[i]/10./10.)*exp(-y[j]*y[j]/10./10.);
            fprintf(fp2,"%lf\t%lf\t%lf\n",x[i],y[j],M[i][j]);
        }
    // printf("\n");
    }

    fclose(fp2);

}

The problem is that you don't use pointers. When you have N as 1022 the variable M will be 8355872 bytes large, and on eg Linux the default process stack space (in which local variables are stored) is 8MB (ie just a little bit more than the space needed by your matrix M when N is 1022).

Other platforms have even smaller default stack sizes (Windows, using the VC++ compiler, defaults to only 1MB).


There are two ways of solving this: Either make your array(s) and matrix(es) global variables (then they will not be on the stack any more), or use pointers and allocate dynamically off the heap.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM