title: Static pointer to dynamically allocated buffer inside function
body: <p>I have a function in C that dynamically allocates a buffer, which is passed to another function to store its return value. Something like the following dummy example:</p>
  
  <pre><code>void other_function(float in, float *out, int out_len) {
      /* Fills 'out' with 'out_len' values calculated from 'in' */
  }
  
  void function(float *data, int data_len, float *out) {
      float *buf;
      int buf_len = 2 * data_len, i;
      buf = malloc(sizeof(float) * buf_len);
  
      for (i = 0; i &lt; data_len; i++, data++, out++) {
          other_function(*data, buf, buf_len);
          /* Do some other stuff with the contents of buf and write to *out */
      }
      free buf;
  }
  </code></pre>
  
  <p><code>function</code> is called by an iterator over a multi-dimensional array (it's a NumPy gufunc kernel, to be precise), so it gets called millions of times with the same value for <code>data_len</code>. It seems wasteful to be creating and destroying the buffer over and over again. I would normally move allocation of the buffer to the function that calls <code>function</code>, and pass a poiinter to it, but I don't directly control that, so not possible. Instead, I am considering doing the following:</p>
  
  <pre><code>void function(float *data, int data_len, float *out) {
      static float *buf = NULL;
      static int buf_len = 0;
      int i;
      if (buf_len != 2 * data_len) {
          buf_len = 2 * data_len;
          buf = realloc(buf, sizeof(float) * buf_len); /* same as malloc if buf == NULL */
      }
      for (i = 0; i &lt; data_len; i++, data++, out++) {
          other_function(*data, buf, buf_len);
          /* Do some other stuff with the contents of buf and write to *out */
      }
  }
  </code></pre>
  
  <p>That means that I never directly free the memory I allocate: it gets reused in subsequent calls, and then lingers there until my program exits. It doesn't seem like the right thing to do, but not too bad either, as the amount of memory allocated is always going to be small. Am I over worrying? Is there a better approach to this?</p>