0

The following code produces segmentation fault 11 when run, I couldn't figure out why. Could anyone offer some insight? Thanks in advance.

#include <stdio.h>
int main() {
int s, e;
int i,j;
typedef struct coordinate {
   int x;
   int y;
} coordinate;

typedef struct cell {
   int altitude;
   coordinate lowest_neighbor;
   int visited;
   int basin;
} cell;

cell cells[1000][1000];
for (i = 0; i < 1000; i++){
    for (j = 0; j < 1000; j++){
        cells[i][j].altitude = 9;
    }
}
printf("%d", cells[0][0].altitude);


return 0;

}

Dan
  • 1
  • 1
    Duplicate of [Creating an 2-dimensional array of a struct results in crash](http://stackoverflow.com/questions/18923339/creating-an-2-dimensional-array-of-a-struct-results-in-crash) (and *many* others). – WhozCraig Mar 26 '14 at 04:50

1 Answers1

1

Because this:

cell cells[1000][1000];

is blowing out your stack. Assuming a four-byte int with no padding in the structures, that array takes up twenty million bytes, quite a lot for a stack.

As a quick fix (for this program anyway), try out:

static cell cells[1000][1000];

which, for many implementations, will take it off the stack.

There are downsides to this approach in general as that means there is only one copy of the array, not one per function call or thread, but that won't matter here since your program only creates it once anyway.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • Thank you very much. How would this problem be solved with dynamic memory allocation? Would that be the most appropriate approach? – Dan Mar 26 '14 at 04:51