user228938
user228938

Reputation: 187

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.

Upvotes: 6

Views: 452

Answers (5)

user333453
user333453

Reputation: 51

Usually, in similar cases you must declare the variable static:

int main(void) {
    static struct foo bar[SIZE];

    return 0;
}

Thus the variable will have been allocated and inserted into static area in compiled time.

Upvotes: 0

Jerry Coffin
Jerry Coffin

Reputation: 490603

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++.

Upvotes: 4

Paulo Neves
Paulo Neves

Reputation: 1196

If you indeed have the size of your data and insist on having it stack allocated perhaps setting the stack size on the linker would be an option. If i am wrong please correct me as i find this topic interesting

Upvotes: 0

sbi
sbi

Reputation: 224159

On my machine, this code

typedef struct {
    char data[65536*4];
} Level;

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

int main (...)
{
     Game g;

     return 0;
}

crashes, while it doesn't if I change the size of the levels array to 3.

You should either reduce the size of your Level type (by putting data on the heap instead of the stack) or putting your levels on the heap (by keeping them in an array of pointers to dynamically allocated Level objects).

Upvotes: 4

nonpolynomial237
nonpolynomial237

Reputation: 2169

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

Upvotes: 5

Related Questions