title: Is this the correct way to return an array of structs from a function?
body: <p>As the title says (and suggests), I'm new to C and I'm trying to return an arbitrary sized array of structs from a function. I chose to use <code>malloc</code>, as someone on the internet, whose cleverer than me, pointed out that unless I allocate to the heap, the array will be destroyed when <code>points_on_circle</code> finishes executing, and a useless pointer will be returned.</p>
  
  <p>The code I'm presenting used to work, but now I'm calling the function more and more in my code, I'm getting a runtime error <code>./main: free(): invalid next size (normal): 0x0a00e380</code>. I'm guessing this is down to my hacked-together implementation of arrays/pointers.</p>
  
  <p>I'm not calling <code>free</code> as of yet, as many of the arrays I'm building will need to persist throughout the life of the program (I <strong>will</strong> be adding <code>free()</code> calls to the remainder!).</p>
  
  <pre><code>xy* points_on_circle(int amount, float radius)
  {
    xy* array = malloc(sizeof(xy) * amount);
  
    float space = (PI * 2) / amount;
  
    while (amount-- &gt;= 0) {
      float theta = space * amount;
  
      array[amount].x = sin(theta) * radius;
      array[amount].y = cos(theta) * radius;
    }
  
    return array;
  }
  </code></pre>
  
  <p>My ground-breaking <code>xy</code> struct is defined as follows:</p>
  
  <pre><code>typedef struct { float x; float y; } xy;
  </code></pre>
  
  <p>And an example of how I'm calling the function is as follows:</p>
  
  <pre><code>xy * outer_points = points_on_circle(360, 5.0);
  for(;i&lt;360;i++) {
      //outer_points[i].x
      //outer_points[i].y
  }
  </code></pre>
  
  <p>A <em>pointer</em> in the right direction would be appreciated. </p>