title: C - Freeing memory after strdup()
body: <p>I'm doing a lesson from the <em>Learn C the Hard way</em> online course.  In the code sample below, I don't understand why the two <code>free()</code> calls are necessary.  I thought one would only need to call <code>free()</code> once, because only one <code>malloc()</code> occurs.  Could somebody clarify why we need two?</p>
  
  <p>If I comment out <code>free(who-&gt;name);</code> then <code>valgrind</code> tells me that I've lost a chunk 'o memory, like so;</p>
  
  <pre><code>LEAK SUMMARY:
  definitely lost: 21 bytes in 2 blocks
  </code></pre>
  
  <p>Here's the code: </p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;assert.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;string.h&gt;
  
  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-&gt;name = strdup(name);
      who-&gt;age = age;
      who-&gt;height = height;
      who-&gt;weight = weight;
  
      return who;
  }
  
  void Person_destroy(struct Person *who)
  {
      assert(who != NULL);
  
      free(who-&gt;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;
  }
  </code></pre>