title: Freeing dynamically allocated memory in C while using linked lists
body: <p>I'm trying to familiarize myself with linked lists in C by experimenting with various cases and I have a question. I have written this code and I'm not sure which is the correct way to free the dynamically allocated memory. Just free (S); or do I have to write free (Top); as well and, if yes, does the order of these two commands matter? Also, apart from that, is this code properly written? I would like a thorough explanation if you don't mind, I haven't coded anything for 5 years. </p>
  
  <pre><code>#include &lt;stdlib.h&gt;
  #include &lt;stdio.h&gt;
  
  typedef char StackType;
  
  typedef struct StackNodeTag
     {StackType T;
      struct StackNodeTag *Link;
     } StackNode;
  
  typedef struct StackTag
     {struct StackNodeTag *Top;
     } Stack;
  
  typedef Stack *StackPointer;
  
  int main (void)
     {StackPointer S;
  
      S = malloc (sizeof (Stack));
      S-&gt;Top = malloc (sizeof (StackNode));
  
      S-&gt;Top-&gt;T = 'c';
      S-&gt;Top-&gt;Link = NULL;
  
      free (S-&gt;Top);
      free (S);
  
      return 0;
     }
  </code></pre>