title: Freeing Dynamically Allocated Struct with Flexible Array Member
body: <p>I have a data structure that is defined as follows:</p>
  
  <pre><code>struct varr {
      int n; //length of data array
      double data[];
  };
  </code></pre>
  
  <p>The data array is required to be initially of size 1 but allowing the possibility of increase.</p>
  
  <p>When allocating space for a <code>struct varr *</code> I use </p>
  
  <pre><code>struct varr *p = malloc(sizeof(struct varr) + sizeof(double));
  </code></pre>
  
  <p>When reallocating space to increase the size of the data array I use</p>
  
  <pre><code>p = realloc(p, sizeof(struct varr) + p-&gt;n * sizeof(double));//p-&gt;n having already been set
  </code></pre>
  
  <p>My question is "how should I free the memory allocated for this structure?"</p>
  
  <p>I've tried a simple <code>free(p);</code> but this causes memory leaks according to memcheck. Is there something fundamentally wrong with how I'm structuring my data for this purpose, or with how I'm allocating the memory?</p>
  
  <p><strong>==NOTE==</strong></p>
  
  <p>I've solved the problem by using a pointer instead of an explicitly declared array. I'd still be interested in a concise answer for why this doesn't work, however.</p>