SwiftCore
SwiftCore

Reputation: 667

Unexplainable segmentation fault

I'm getting a segmentation fault here for some reason. I have no idea why. Any help?

typedef struct gw_struct{
    int pop;
    int col;
    int row;
    struct district ***gw;
    struct person **people;
};

typedef struct gw_struct *GW;

and then later in a function...

GW world;
struct district ***array = malloc(nrows*sizeof(struct district**));
    int i, j;
for (i = 0; i < nrows; i++)
{
    array[i] = malloc(ncols*sizeof(struct district*));
    for (j = 0; j<ncols; j++)
    {
            array[i][j] = malloc(sizeof(struct district));
    }
}   

world->gw = array; //this is the line that gives the seg fault

Upvotes: 0

Views: 119

Answers (2)

godzilla3000
godzilla3000

Reputation: 246

Your issue is on the first line GW world;, this is not properly referenced in memory.

This should work:

GW *world;
struct district ***array = malloc(nrows*sizeof(struct district**));
    int i, j;
for (i = 0; i < nrows; i++)
{
    array[i] = malloc(ncols*sizeof(struct district*));
    for (j = 0; j<ncols; j++)
    {
            array[i][j] = malloc(sizeof(struct district));
    }
}   

world->gw = array; //this is the line that gives the seg fault

Your World variable declaration needs to be a pointer, this will properly reference your initialized struct in memory and will allow you to make your assignment.

Upvotes: -1

Carl Norum
Carl Norum

Reputation: 224844

Your code doesn't initialize world, so presumably it points off into the weeds someplace when you try to dereference it in that line. Make sure to intialize variables before you use them.

Upvotes: 2

Related Questions