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
}
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 malloc
ed 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 malloc
ed, don't forget to free
.
You should pass by reference:
static void create_ship(struct ship **ship);
and
create_ship(&game.ship);
otherwise the allocated structure is discarded.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With