segmentation fault for 2D arrays

前端 未结 3 1915
慢半拍i
慢半拍i 2020-12-07 06:22

I want to define a 2D array of very big size. But it is giving me segmentation fault?

  #include 

  int main () {
       int i;
       int te         


        
相关标签:
3条回答
  • 2020-12-07 06:27

    You can allocate the whole table in only one array but you won't be able to access array data with indices using two square brackets:

    int * temp = malloc(4000*5000*sizeof(int));
    

    to access the element (i,j) where previously you wrote temp[i][j], now you should now compute the index the following way:

    temp[i*5000+j];
    

    and do not forget to free the memory allocated for your table afterward:

    free(temp);
    
    0 讨论(0)
  • 2020-12-07 06:30
    int temp[4000][5000];
    

    That's a VERY BIG array, way bigger than the normal size of stack, you get a segmentation fault because of stack overflow. Consider using dynamic allocation instead.

    0 讨论(0)
  • 2020-12-07 06:37

    You need to use dynamic allocated arrays for such big arrays.

    Try:

    int* temp[4000];
    for(i = 0; i < 4000; ++i) temp[i] = malloc(5000 * sizeof(int));
    ...
    for(i = 0; i < 4000; ++i) free(temp[i]).
    

    Whole program with error checking:

    int main () {
        int i, j;
        int* temp[4000];
        for (i = 0; i < 4000; ++i)
        {
            temp[i] = malloc(5000 * sizeof(int));
            if (temp[i] == NULL)
            {
                for (j = 0; j < i; ++j) free(temp[i]);
                exit(1);
            }
        }
        for (i = 0; i < 5; i++)
        {
            printf ("Hello World\n");
        }
    
        for (i = 0; i < 4000; ++i) free(temp[i]);
    }
    

    Here you can find function which would use single malloc call to allocate two dimension array.

    And simpler version of my own:

    int main () {
        int i, j;
        int* temp[4000];
        int* array = malloc(4000 * 5000 * sizeof(int));
        if (malloc_tmp == NULL) exit(1);
        for (i = 0; i < 4000; ++i)
        {
            temp[i] = array + (i * 5000);
        }
        for (i = 0; i < 5; i++)
        {
            printf ("Hello World\n");
        }
    
        free(temp[0]);
    }
    
    0 讨论(0)
提交回复
热议问题