title: Why is memory being leaked in my C reverse list function?
body: <p>I'm fairly new to Pointers and the memory model so excuse me if this is obvious, but I am writing a program to test a function reverse that reverses a list. Anyway I have it in three files, C5.c, C5-driver.c, and C5.h. Here they are in that order:</p>
  
  <pre><code>#include "C5.h"
  #include &lt;stdlib.h&gt;
  #include &lt;stdio.h&gt;
  
  struct node *cons(int fst, struct node *rst) {
      struct node *new = malloc(sizeof(struct node));
      if (new == NULL) {
          printf("cons: out of memory\n");
          abort();
      }
      (*new).first = fst; /* same as (*new).first = fst */
      (*new).rest = rst;
      return new;
  }
  
  struct node *reverse(struct node *lst) {
      struct node *ans = NULL;
      while (lst != NULL) {
          ans = cons((*lst).first, ans);
          lst = (*lst).rest;
      }    
      return ans;
  }
  
  void free_list(struct node *lst) {
      struct node *p;
      while (lst != NULL) {
          p = lst-&gt;rest;
          free(lst);
          lst = p;
      }
  }
  
  void print_list(struct node *lst) {
      printf("( "); 
      while (lst != NULL) {
          printf("%d ", (*lst).first);
          lst = (*lst).rest;
      }
      printf(")\n");
  }
  </code></pre>
  
  <p><pre></p>
  
  <p>C5-driver.c</p>
  
  <pre><code>#include &lt;stdlib.h&gt;
  #include &lt;stdio.h&gt;
  #include "C5.h"
  
  int main() {
      struct node *lst1 = cons(5, NULL);
      struct node *lst2 = cons(3, lst1);
      struct node *lst3 = cons(1, lst2);
      print_list(lst3);
      lst3 = reverse(lst3);
      print_list(lst3);
      free_list(lst3);
  }
  </code></pre>
  
  <p>C5.h</p>
  
  <code>struct node {
      int first;
      struct node *rest;
  };
  
  struct node *cons(int ,struct node *);
  struct node *reverse(struct node *);
  void print_list(struct node *);
  void free_list(struct node *);
  </code></pre>
  
  <p>However I'm told by XCode that there are memory leaks.</p>
  
  <p>I'm assuming it's after cons is used however I've tried creating a new <code>struct node *ans = new</code> and free(new); with return ans; but that doesn't work. I've also tried free_list as you can see above.</p>
  
  <p>Thanks~</p>