title: Free memory allocated in a different function?
body: <p>I'm trying to learn C and I'm currently trying to write a basic stack data structure, but I can't seem to get basic <code>malloc</code>/<code>free</code> right.</p>
  
  <p>Here's the code I've been using (I'm just posting a small part here to illustrate a specific problem, not the total code, but the error message was generated just by running this example code in <code>valgrind</code>)</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  typedef struct Entry {
      struct Entry *previous;
      int value;
  } Entry;
  
  void destroyEntry(Entry entry);
  
  int main(int argc, char *argv[])
  {
      Entry* apple;
      apple = malloc(sizeof(Entry));
      destroyEntry(*(apple));
      return 0;
  }
  
  void destroyEntry(Entry entry)
  {
      Entry *entry_ptr = &amp;entry;
      free(entry_ptr);
      return;
  }
  </code></pre>
  
  <p>When I run it through <code>valgrind</code> with <code>--leak-check=full --track-origins=yes</code>, I get the following error:</p>
  
  <pre class="lang-none prettyprint-override"><code>==20674== Invalid free() / delete / delete[] / realloc()
  ==20674==    at 0x4028E58: free (vg_replace_malloc.c:427)
  ==20674==    by 0x80485B2: destroyEntry (testing.c:53)
  ==20674==    by 0x8048477: main (testing.c:26)
  ==20674==  Address 0xbecc0070 is on thread 1's stack
  </code></pre>
  
  <p>I think this error means that the <code>destroyEntry</code> function is not allowed to modify memory allocated explicitly in main. Is that right? Why can't I just <code>free</code> the memory I allocated in <code>main</code> in another function? (and is this behavior somehow specific to main?)</p>