I have got a segmentation fault after initializing a 2d array. I did some research but I have no clue how to fix this, can someone help me out?
The max length of my array is 10000 and must be set by variable length.
My code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
//Set dimension of matrices
int length = 10000;
double matrix1[length][length];
//This line ends up in segmentation fault.
memset( matrix1, 0, length*length*sizeof(double));
return 0;
}
Modern C compilers allocate local variables on the stack, which has a finite size. Your variable double matrix1[length][length]
is too large to fit, which causes stack overflow and results in segmentation fault. (Yes, you get segfault even before the call to memset
.) Either make matrix1
a global variable or use dynamic memory allocation with malloc
. In fact, if you use calloc
instead of malloc
, there will be no need for memset
.
One more option is to change the default stack size.