Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nested structures and pointers

I dork this up just about every time I jump back into a C project. I'm getting a segfault when attempting to access a structure within a structure. Let's say I have the following (simplified) structures for a game:

struct vector {
    float x;
    float y;
};

struct ship {
    struct vector *position;
};

struct game {
    struct ship *ship;
} game;

And a function to initialize the ship:

static void
create_ship(struct ship *ship)
{
    ship = malloc(sizeof(struct ship));
    ship->position = malloc(sizeof(struct vector));
    ship->position->x = 10.0;
}

Then down in main():

int main() {
    create_ship(game.ship);
    printf("%f\n", game.ship->position->x); // <-- SEGFAULT
}
like image 284
ben lemasurier Avatar asked Oct 02 '12 17:10

ben lemasurier


2 Answers

You are passing game.ship by value, so inside create_ship the variable ship is just a copy of that pointer, and it just changes the copy. When the function returns, the pointer to what you malloced is lost and the effects of the function are not visible outside it, except for the memory leak.

You need to pass a pointer to the pointer and modify game.ship through that:

static void
create_ship(struct ship **ship)
{
    *ship = malloc(sizeof(struct ship));
    (*ship)->position = malloc(sizeof(struct vector));
    (*ship)->position->x = 10.0;
}

And

create_ship(&game.ship);

Or perhaps a better way would be to do as Johnny Mopp suggests in the comments, return the pointer from the function instead of modifying one outside of it:

static struct ship* create_ship()
{
    struct ship* s = malloc(sizeof(struct ship));
    s->position = malloc(sizeof(struct vector));
    s->position->x = 10.0;

    return s;
}

And

game.ship = create_ship();

And of course, what you have malloced, don't forget to free.

like image 115
Seth Carnegie Avatar answered Sep 19 '22 02:09

Seth Carnegie


You should pass by reference:

static void create_ship(struct ship **ship);

and

create_ship(&game.ship);

otherwise the allocated structure is discarded.

like image 41
Michael Krelin - hacker Avatar answered Sep 21 '22 02:09

Michael Krelin - hacker