title: Possible to both return and free a dynamically allocated array in C?
body: <p>Is it possible to both return and free a dynamically allocated array?</p>
  
  <pre><code>int *mycopy(int *from, int len)
  {
      int i;
      int *to;
  
      to = malloc(len*sizeof(int));
  
      for(i = 0; i &lt; len; ++i) {
          to[i] = from[i]
      }
  
      return to;
  
      // how do I free the "to" array?
      // do i even need to, or does the array only have function scope
      // and get deleted when the function exits?
  }
  </code></pre>
  
  <p>Or is</p>
  
  <pre><code>void mycopy(int *from, int *to, int len);
  </code></pre>
  
  <p>my only option?</p>
  
  <p>The mycopy function is just a simple example but in the real code I want to nest them such as calling it like</p>
  
  <pre><code>a = mycopy(mycopy(b, 5), 5)
  </code></pre>
  
  <p>How do I do this without allocating more memory every time the function is called? Thanks.</p>