A segmentation fault error with 2D array

前端 未结 2 1218
情书的邮戳
情书的邮戳 2021-01-22 16:07

There is a weird segmentation fault error. The following code runs fine

#include  
#include 
main()
    {
    int matrixSize = 100         


        
相关标签:
2条回答
  • 2021-01-22 16:36

    You are exceeding the stack size most likely.

    In the terminal you are using to run this, try typing

    ulimit -s unlimited

    and re-run, assuming you are on a Linux system using bash (or sh).

    If you have to use arrays that size, you can make them dynamic so they are on the heap rather than the stack if changing the stack size is problematic for some reason.

    0 讨论(0)
  • 2021-01-22 16:53

    As tpg2114 says allocating as large matrices is not a good idea. Easiest is to allocate it like that

    double (*a)[matrixSize] = malloc(sizeof(double[matrixSize][matrixSize]));
    .
    free(a);
    

    Then you can continue to use your nested for loops for initialization without problems as before.

    NB:

    • since you use a variable for the dimensions your matrix is technically a variable length array, that is only available with C99
    • your definition for main is not conforming to the standard. In your case you should use int main(void) { ... }. since a conforming compiler should capture this, it looks that you don't use the correct options for your compiler or that you ignore warnings that he gives you.
    • since they are representing sizes, your variables matrixSize, i and j should be of type size_t and not int.
    0 讨论(0)
提交回复
热议问题