Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Segmentation fault problem (C)

I have a struct named Game with an array of levels, defined like this:

typedef struct 
{
     Level levels[x];
} Game;

When I compile the code, if x is 1, 2 or 3, the program runs normally. If it's any other value (4, for instance), I get a segmentation fault. I'm not accessing the array anywhere. Main is something like this at the moment (commented everything except the initialization):

int main (...)
{
     Game g;

     return 0;
}

Any clue of what this might be?

Thanks in advance.

like image 853
user228938 Avatar asked May 14 '10 16:05

user228938


2 Answers

If the Level class/struct is really big, you could try using this:

typedef struct {
    Level *levels;
} Game;

and then allocating your levels with malloc() or new. Or if you really need an array of levels:

typedef struct {
    Level* levels[NUM_LEVELS];
} Game;

then allocating levels with something like this:

// Allocate levels
int i;
for(i=0;i<NUM_LEVELS;i++) {
    gameStruct.levels[i] = (Level*)malloc(sizeof(Level));
    initLevelNum(gameStruct.levels[i], i);
}
like image 96
nonpolynomial237 Avatar answered Sep 29 '22 02:09

nonpolynomial237


How big is a Level? Is it possible you're overflowing your stack? Given that there's (apparently) only ever one Game object anyway, perhaps you'd be better off using the static storage class, as in: static Game g;

Edit: If you want to force allocation on the heap, I'd advise using std::vector<Level> levels; rather than using pointers directly. Oops -- missed it's being tagged C, not C++.

like image 44
Jerry Coffin Avatar answered Sep 29 '22 02:09

Jerry Coffin