Could not allocate memory

前端 未结 3 1521
-上瘾入骨i
-上瘾入骨i 2021-01-22 17:15

In my C code I am allocating memory for 2d array double E[2000][2000]; but when I run it gets a runtime error Segmentation fault(core dumped) and when

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-22 18:06

    I assume you are allocating it on the stack by simply

    double E[2000][2000];
    

    which will probably be more than stack size allocated to your program.

    Try using malloc (or new in c++) or increase the default stack size of your program using options. gcc can be configured using setrlimit() for this purpose.

    setting stack size in gcc

    Keep in mind that even if stack size is increased, an array of this size should be global

    You can also use a single statement to allocate a 2D array on heap if one dimension is fixed in size

    double (* E)[COLUMN_SIZE];
    int rows = 20; // this is dynamic and can be input from user at run time
    E = malloc(rows * sizeof(*E)); // this needs to be freed latter
    

    A more detailed similar example allocating 2d array without loops

提交回复
热议问题