variable name change causes segfault
06:49 05 Dec 2025

Okay it probably does'nt. That would be weird. I'm guessing, I'm allocating my memory wrong somehow.

I have two Structs. In one there is a pointer member, that points to the other. Here they are.

typedef struct card{
    int value;
} card;

typedef struct player{
    card* hand;
    int value;
} player;

To put it on SO, I tried renaming card, player and hand to something like foo and bar, but then the error doesn't occur anymore.

Here is what I do:

player* player = malloc(sizeof(player)*5);
    for(int playerIndex = 0; playerIndex < 5; playerIndex++){
        player[playerIndex].hand = malloc(sizeof(card)*(12));
    }

I allocate some memory. And then I try to access it.

for(int i = 0; i < 12; i++){
    for(int j = 0; j < 5; j++){
        player[j].hand[i].value = 0;
    }
}

I think it's important to note, that removing the second variable from the player struct also fixes the problem.

I have also checked if the pointers returned from malloc() are == NULL. They are not.

I hope, I haven't overlooked something obvious. Thank's in regards.

c struct segmentation-fault malloc