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;
}
You’re returning the address of a local variable.
You can either modify your
new_personto take an argument (a pointer to a person) or you canmallocone inside the function and manipulate that.The person you declared in your function goes out of scope when the function returns. Everything that happens to it after that is undefined. It might coincidentally keep its value for a while, but you should not depend on this. When you make your call to printf, the stack grows and overwrites the old location of your person with new stuff.