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.shipby value, so insidecreate_shipthe variableshipis just a copy of that pointer, and it just changes the copy. When the function returns, the pointer to what youmalloced 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.shipthrough that:And
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:
And
And of course, what you have
malloced, don’t forget tofree.