简体   繁体   中英

segmentation fault for 2D arrays

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

  #include <stdio.h>

  int main () {
       int i;
       int temp[4000][5000];
      for (i = 0; i < 5; i++)
      {
          printf ("Hello World\n");
      }
  }

Can anyone please suggest me some other way? Is there some problem with memory initialization? Thanks in advance

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);
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.

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]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM