title: flexible mpz_t array in struct
body: <p>I have a struct like this:</p>
  
  <pre><code>typedef struct{
      size_t length; // length of the array
      size_t numbits; // number of bits allocated per val in vals
      mpz_t vals[]; // flexible array to hold some number of mpz_t array
  } CoolArray;
  </code></pre>
  
  <p>Ok, so it's a normal flexible array, and I should be able to use malloc to set
  it's size:</p>
  
  <pre><code>void initArray(CoolArray* array, size_t length, size_t numbits){
      assert(length&gt;=1); // don't make arrays with a length&lt;=0
  
      // first I allocate memory for vals...
      array-&gt;vals = (mpz_t*) malloc(sizeof(CoolArray)+length*sizeof(mpz_t));
  
      // then I allocate memory for each val in vals
      mpz_array_init(array-&gt;vals, (size_t)length, numbits);
  
      return;
  }
  </code></pre>
  
  <p>but when I try to use this, I get a segmentation fault. I also get complaints
  about incorrect use of mpz_array_init. But I've looked at the manula, and it
  seems I am doing this correctly.</p>
  
  <p>I also tried to use my struct like this:</p>
  
  <pre><code>typedef struct{
      size_t length; // length of the array
      size_t numbits; // number of bits allocated per val in vals
      mpz_t* vals; // pointer to start of array
  } CoolArray;
  </code></pre>
  
  <p>and I also changed my <code>initArray</code> function to this:</p>
  
  <pre><code>void initArray(CoolArray* array, size_t length, size_t numbits) {
      assert(length&gt;=1); // don't make arrays with a length&lt;=0
  
      // first I allocate memory for vals...
      array-&gt;vals = (mpz_t*) calloc(length, sizeof(mpz_t));
  
      // then I allocate memory for each val in vals
      mpz_array_init(array-&gt;vals, (size_t)length, numbits);
  
      return;
  }
  </code></pre>
  
  <p>This one doesn't segfault, but I get complaints at compile time about
  incorrect usage of <code>mpz_array_init</code>, and I also get a bunch of <code>malloc</code> errors
  in my output, along with the output I want to see. Can anyone tell me where my
  code is incorrect? why does the first version segfault? I did it the way
  people seem to recommend. And why does the compiler complain about
  <code>mpz_array_init</code> being used incorrectly?</p>
  
  <p>This is the sort of error i get in my output:</p>
  
  <pre><code>gmpascal(80964) malloc: *** error for object 0x100801088: Non-aligned
  pointer being freed *** set a breakpoint in malloc_error_break to debug
  </code></pre>
  
  <p><strong>P.S.</strong> <code>gmpascal</code> is the name of my executable, it computes the nth row of
  pascals triangle.</p>
  
  <p><strong>P.P.S.</strong> I'm compiling with <code>gcc-4.2</code> on a <strong>Powermac</strong> with these flags:</p>
  
  <pre><code>-arch ppc64 -o gmpascal gmpascal.c -lgmp -Wall
  </code></pre>
  
  <p>Is there something I missing here?</p>