title: When use malloc for a static pointer inside a function?
body: <p>I don't understand why, in the following code snippet, the programmer used a static variable (and as a consequence I started to doubt all my little knowledge):</p>
  
  <pre><code>int func (...) {
      static unsigned int *temp = NULL;
  
      if( temp == NULL ) {
          temp = malloc(dim*sizeof(*temp));
      }
  
      // do stuff with temp
  
  }
  </code></pre>
  
  <p>In main(), <em>func</em> is called several time in a loop:</p>
  
  <pre><code>int main() {
  
      for (i = 0; i &lt; N; ++i)
          x = func(...);
  
  }
  </code></pre>
  
  <p>The first call to <em>func</em> initialise the variable temp to NULL and thus temp is allocated (maybe the initialisation is also redundant (according to this <a href="https://stackoverflow.com/questions/17012707/initialization-global-and-static-variable-to-0-is-always-unnecessary">post</a>). </p>
  
  <p>The function <em>func</em> doesn't do anything special with temp, just copy some values to it from another (global) array if a condition is met and return the number of elements written.</p>
  
  <p>If I understand correctly, malloc allocates the memory in the heap, thus the memory will be persistent until it is explicitly freed and as the pointer is static it can be accessed in subsequent calls.</p>
  
  <p>Then the questions:</p>
  
  <ol>
  <li>Do I understand it correctly?</li>
  <li>Which is the advantage of this approach instead of malloc temp
  outside <em>func</em> and then explicitly pass it to <em>func</em>? I guess it
  depends on circumstances, ok, but maybe there is a well known
  example. I also saw this <a href="https://stackoverflow.com/questions/1286515/extern-and-static-pointers-in-c">answer</a> but I cannot understand the
  usefulness of the first example.</li>
  <li>I must free temp inside <em>func</em> (at the last step, which, by the way, is not done in this code)?</li>
  </ol>
  
  <p>I need to modify the code above (which is a lot more complex) and I prefer to allocate temp outside func and then pass it to the function and I want to be sure that I am not missing something important. By the way I thought I could learn something :). </p>
  
  <p>Thanks.</p>