29
#include <stdio.h>
#define N 1024
int main(){
  int i, j;
  int a[N][N];
  int b[N][N];
  for (i=0;i<N;i++){
    a[i][i]=i;
    b[i][i]=i;
  }
  for (i=0;i<N;i++)
    for(j=0;j<N;j++)
    {
         printf("%d", a[i][j]);
         printf("%d", b[i][j]);
    }
  return 0;
}

This program is a reason of segmentation fault, but if I define N as 1023, program will work correctly. Why it happens?

cnicutar
  • 178,505
  • 25
  • 365
  • 392
Alexey Matveev
  • 519
  • 1
  • 5
  • 13

1 Answers1

40

You are overflowing the stack. 2 * 1024 * 1024 * sizeof(int) is a lot for most systems.

The simplest solution would be to make the arrays static.

static int a[N][N];
static int b[N][N];

Other methods:

  • Make the arrays global (this is essentially the same as the above)
  • Use malloc in a loop and of course remember to free

    int **a = malloc(N * sizeof *a);
    for (i = 0; i < N; i++)
        a[i] = malloc(N * sizeof *a[i]);
    
cnicutar
  • 178,505
  • 25
  • 365
  • 392
  • 1
    @AlexeyMatveev OR you can tell the compiler to give you a bigger stack! There is an option for that! – xanatos Oct 26 '11 at 12:19
  • 2
    @xanatos: it's not necessarily up to the compiler - in many environments stack size is determined at run-time – Paul R Oct 26 '11 at 12:28
  • @xanatos Picking up where @PaulR left, for instance on Unix this is set using `ulimit -s`. – cnicutar Oct 26 '11 at 12:29
  • static int p[20000000]; causes the following error: variable length array declaration can not have 'static' storage duration. How is this different from the suggestion? – Michal May 17 '14 at 19:37
  • @Michal No it won't. That error will arise when you use `static` for a [Variable Length Array](https://en.m.wikipedia.org/wiki/Variable-length_array). – Spikatrix Oct 18 '15 at 10:51