0

I get a segmentation fault (core dumped) from this algorithm. Why?

Does it work when using small value of N and K? For example, N=100 and K=10?

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

#define N 400       
#define K 30        

int main()
{
int  i,j,k;
int A[K+1][N][N];
for (i=0;i<K+1;i++)
{
  for (j=0;j<N;j++)
  {
      for (k=0;k<N;k++)
      {

           A[i][j][k]=0; 
      }

  }
}
printf("A[%i][%i][%i] \n", i, j,k);
printf("OK");
return 0;
}

3 Answers3

6

You are likely exceeding the stack size.

If you are using large values for K and N, consider putting A on the heap.

int *A = malloc((K+1) * N * N * sizeof(int));

To index into it:

A[(i*(K+1) + j)*N + k]=0;

(you make want to make a function or macro for that)

And once you are done with A,

free(A);
Paul Draper
  • 78,542
  • 46
  • 206
  • 285
2

You are trying to create an array with size of 19.2 MB (31*400*400 *4) where 4B is the size of type int. It is not possible to statically allocate more than 8.37MB, use malloc instead.

Hhyperion
  • 666
  • 5
  • 6
  • Did you mean *not* possible? And stack size varies (widely). – Paul Draper Nov 09 '13 at 23:16
  • In Windows the stack defaults to 1MB. – Havenard Nov 09 '13 at 23:17
  • @PaulDraper: I expect he was thinking of `static int A[K+1][N][N];` either at file or function scope. Because they aren't on the stack, the don't blow the stack away, unlike the on-stack (for normal machines) allocation of automatic local variables. – Jonathan Leffler Nov 09 '13 at 23:24
0

Another way is to just move the array off of the stack and into the data segment:

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

#define N 400       
#define K 30        
int A[K+1][N][N];  // ADD THIS LINE

int main()
{
int  i,j,k;
// REMOVE THIS LINE int A[K+1][N][N];
for (i=0;i<K+1;i++)
{
  for (j=0;j<N;j++)
  {
      for (k=0;k<N;k++)
      {

           A[i][j][k]=0; 
      }

  }
}
printf("A[%i][%i][%i] \n", i, j,k);
printf("OK");
return 0;
}
Charlie Burns
  • 6,994
  • 20
  • 29