0

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;
}
jrd1
  • 10,358
  • 4
  • 34
  • 51
Cees Mandjes
  • 195
  • 12

1 Answers1

2

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.

DYZ
  • 55,249
  • 10
  • 64
  • 93
  • Specifically, a matrix of type `double[10000][10000]` is roughly 800 MB. A typical stack size is 8 MB. –  Feb 04 '18 at 03:27
  • Gotcha, thank. I made it work with: double *matrix1 = (double *)malloc(length*length*sizeof(double)); – Cees Mandjes Feb 04 '18 at 03:28