I couldn't think of a proper title to my question so here it goes. I am trying to learn C and the following code is from the tutorial I am following.
struct Person {
char *name;
int age;
int height;
int weight;
};
struct Person *Person_create(char *name, int age, int height, int weight){
struct Person *who = malloc(sizeof(struct Person));
assert(who != NULL);
who->name = strdup(name);
who->age = age;
who->height = height;
who->weight = weight;
return who;
}
void Person_destroy(struct Person *who){
assert(who != NULL);
free(who->name);
free(who);
}
int main(int argc, char *argv[]){
struct Person *joe = Person_create("Joe Alex", 32, 64, 140);
........
My question is in Person_create
function why are we duplicating name
to a new memory location for who->name
. Why can't we just make who->name
point to the same location provided by the *name
supplied to the function.
Also if we directly assigned the address of *name
to who->name
do we have to free it in Person_destroy
.