segmentation fault for 2D arrays

前端 未结 3 1944
慢半拍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: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]);
    }
    

提交回复
热议问题