-1

I'm writing a code for finite difference scheme to approximate a PDE solution. For this purpose I need to create a double array of larger size as I refine my mesh. The problem is that I get Segmentation fault: 11 as I go over double array of size 1000. I created this trivial code to identify my problem. Please let me know how I can work this problem around

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

int main()
{
    int n, a=2000,i=0;
    double T=40;
    double time =25, k = T/(a-1);
    double Array[a][a];
    time=25;
    n=(time/k);
    for(i=0;i<a;i++)
    {
        Array[i][i]= 2+i;
    }
    printf("%d\n", n);
    printf("%lf\n", Array[600][600]);

}

Note that a =1000 or less works just fine. Also my partner is working on fortran and does not encounter the same problem.

Thanks

Cloud
  • 18,753
  • 15
  • 79
  • 153
user2059456
  • 19
  • 1
  • 2
  • 8
  • 5
    Use dynamic arrays. You're blowing the stack. – nneonneo Apr 30 '14 at 18:29
  • 2
    You are creating an array of 4M entries at 8 bytes each, which is 32 MiB, give or take. That is too large for most system's stack (often limited to 8 MiB, sometimes less). Use dynamic allocation, or make it a global variable. (This is a duplicate of a number of other questions -- the difficulty will be finding the duplicate(s).) – Jonathan Leffler Apr 30 '14 at 18:32
  • Thanks.. I'll look up dynamic allocation in C. – user2059456 Apr 30 '14 at 18:48

1 Answers1

0

You may use something like :

  #include <malloc.h>
  ...
  double** Array=malloc(m*sizeof(double*));
  if(Array==NULL){printf("malloc failed\n");}
  Array[0]=malloc(m*n*sizeof(double));
  if(Array[0]==NULL){printf("malloc failed\n");}
  for (i=0;i<m;i++){
      Array[i]=&Array[0][i*n];
  }
  ...
  Array[j][i]=i+j;
  ...
  free(Array[0]);
  free(Array);

malloc is used to allocate memory and free to free it.

Bye,

francis
  • 9,525
  • 2
  • 25
  • 41
  • @PaulGriffiths : All values of `Array[i]` are initialized in the `for` loop ! This way to allocate memory ensures that values are contigous in memory (useful for fftw, lapack), but it makes it harder to resize it. http://stackoverflow.com/questions/15062718/allocate-memory-2d-array-in-function-c – francis Apr 30 '14 at 19:07