1

I have written the following code, which prints an array. But when the input is very large, for example J=40000, I get Segmentation fault. Could you tell me why it happens? Is this because the dimension of the arrays is too big, or have I done something wrong?

    int main(){

    int i,j,J;
    printf("Give the number J: \n");
    scanf("%d", &J);

    double k[J-1];
    double d[J-1];
    double p[J-1];
    double A[J-1][3];       
    double h=1.0/(double)J;

    for(j=0; j<J-1; j++){
        k[j]=-1.0/(h*h);
        d[j]=2.0/(h*h);
        p[j]=-1.0/(h*h);
  }


  for(j=0; j<J-1; j++){
        A[j][0]=k[j];
        A[j][1]=d[j];
        A[j][2]=p[j];
    }


    A[0][0]=0.0; 
    A[J-2][2]=0.0;

    for(j=0; j<J-1; j++){
      for(i=0; i<3; i++){
        printf("%lf  ",A[j][i]);
    }
    printf("\n\n");
}
return 0;
}
Mary Star
  • 375
  • 7
  • 27

2 Answers2

1

Perhaps an issue with stack overflow. Your stack-based arrays k, p, d, and A will need about:

40000 x (1 + 1 + 1 + 3) x 8 = 1920000 bytes

E.g. about two megabytes. The default maximum stack size is typically 1 megabyte.

See e.g. http://msdn.microsoft.com/en-us/library/tdkhxaks.aspx or Change stack size for a C++ application in Linux during compilation with GNU compiler or Getting a stack overflow exception when declaring a large array.

Community
  • 1
  • 1
Joseph Quinsey
  • 9,553
  • 10
  • 54
  • 77
0

If you are programming in C (not C++) declare variables in the middle of the program could bring you problems. Try using malloc() instead to make dynamic arrays.

Another problem I could see is in the next sentence:

    A[J-2][2]=0.0;

if J=1 for example it will bring you problems because index will be lower than 0.

Abend
  • 589
  • 4
  • 14
  • Ok! And how can I use malloc() for a two-dimensional array? – Mary Star Jan 06 '14 at 23:58
  • malloc() reserve memory in number of bytes. Does not matter if it is of one, two or three dimension. For example, if you want to declare: double A[J-1][3]; You will have (J-1)*3 bytes. So you have to use: double *A; A=malloc((J-1)*3); And you will be able to use it as you want (in this case as a bidimensional array) – Abend Jan 07 '14 at 00:05