title: how to free an allocated array in a function in c
body: <p>If we were to use <code>malloc()</code> in <code>main()</code>, we could <code>free()</code> that dynamic memory allocation in <code>main()</code>.</p>
  <p>However, if we use <code>malloc()</code> in a different function
  and  we use that function in <code>main()</code>, where should we call <code>free()</code> to release the memory allocated in that function?</p>
  <p>I.e., in the following source code:</p>
  <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  int * memory_allocate_function(int);
  
  int main(void) {
      int n=5; //length of array, 5 for example.
      int *my_array;
      my_array = memory_allocate_function(n);
      return 0;
  }
  
  int * memory_allocate_function(int n) {
      int i;
      int *array;
      array=(int *)malloc(n * sizeof(int));
      if(array == NULL) {
          printf(&quot;can not allocate memory.&quot;);
          return NULL;
      }
      // I think i can't use &quot;free(array);&quot; in here.
      // Because I need that array in main().
      return array;
  }
  </code></pre>
  <p>Is this the best way to do this?</p>