I have this example file
example.c
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
typedef struct {
char *name;
} player;
void
playercreation(player *p, int nr)
{
p=malloc(sizeof(player));
char stringtemp[10];
printf("Create player %d:\nWrite your name (max 10 letters): ", nr);
scanf("%s", stringtemp);
p->name=malloc(sizeof(*(p->name))*11);
strcpy(p->name, stringtemp);
p->drawnlines=0;
p->squares=0;
}
void
playercreationMenu(player *p1, player *p2)
{
playercreation(p1, 1);
playercreation(p2, 1);
}
void
confirmPlayer(player *p)
{
printf("player %s created\n", p->name);
}
int
main(void)
{
player p1, p2;
playercreationMenu(&p1, &p2);
confirmPlayer(&p1);
confirmPlayer(&p2);
}
In my real program this gives me a segmentation fault as im trying to access something in the player structure that does not exist as the player never is created, but in this example its shown by the fact that the players name is (null) although the name was given in the playercreationMenu function. Why is this?
You write
But in the constructor function, you have
So you’re assigning a
malloc()ated block of memory to the local variable containing the address of an already-allocated (on the stack!) structure… Drop the call tomalloc()and you’ll be fine.You’re also using the
countvariable before initializing it or assigning a value to it:So one, this is undefined behavior, two, you’ll get a quite random amount of memory (which makes it possible to write past its bounds -> another undefined behavior), or a NULL pointer if this would result in too much memory allocated (a third undefined behavior).
Three UBs in one line – do expect it to crash.