i'm obviously not blaming printf here, i probably messed up my mem allocations and access but i can't understand where i did wrong. the program crash on the second printf in main. It also crash on the third if i comment the second one. Actually it crash whenever i access p after the first printf !
Can someone explains me what i am doing wrong ?
Thanks a lot.
typedef struct
{
char * firstname;
char * lastname;
int age;
} person;
person * new_person(char * firstname, char * lastname, int age)
{
person p;
int lf = strlen(firstname);
int ll = strlen(lastname);
p.firstname = (char *)malloc(++lf * sizeof(char));
p.lastname = (char *)malloc(++ll * sizeof(char));
strcpy(p.firstname, firstname);
strcpy(p.lastname, lastname);
p.age = age;
return &p;
}
int main()
{
person * p = new_person("firstname", "last", 28);
printf("nom : %s ; prenom : %s ; age : %d\n", p->lastname, p->firstname, p->age);
printf("nom : %s ; prenom : %s ; age : %d\n", p->lastname, p->firstname, p->age);
printf("nom : %s ; prenom : %s ; age : %d\n", (*p).lastname, (*p).firstname,(*p).age);
return 0;
}