Alexey Matveev Alexey Matveev - 2 months ago 25
C Question

Segmentation Fault, large arrays

#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?

Answer

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]);
    
Comments