I'm doing a lesson from the Learn C the Hard way online course. In the code sample below, I don't understand why the two free()
calls are necessary. I thought one would only need to call free()
once, because only one malloc()
occurs. Could somebody clarify why we need two?
If I comment out free(who->name);
then valgrind
tells me that I've lost a chunk 'o memory, like so;
LEAK SUMMARY:
definitely lost: 21 bytes in 2 blocks
Here's the code:
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
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); /* Why this one??! */
free(who);
}
int main(int argc, char *argv[])
{
// make two people structures
struct Person *joe = Person_create(
"Joe Alex", 32, 64, 140);
struct Person *frank = Person_create(
"Frank Blank", 20, 72, 180);
// destroy them both so we clean up
Person_destroy(joe);
Person_destroy(frank);
return 0;
}