c - Segmentation Fault, large arrays -
#include <stdio.h> #define n 1024 int main(){ int i, j; int a[n][n]; int b[n][n]; (i=0;i<n;i++){ a[i][i]=i; b[i][i]=i; } (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 reason of segmentation fault, if define n 1023, program work correctly. why happens?
you overflowing stack. 2 * 1024 * 1024 * sizeof(int)
lot systems.
the simplest solution make arrays static
.
static int a[n][n]; static int b[n][n];
other methods:
- make arrays global (this same above)
use
malloc
in loop , of course rememberfree
int **a = malloc(n * sizeof *a); (i = 0; < n; i++) a[i] = malloc(n * sizeof *a[i]);
Comments
Post a Comment