title: How to change values of flexible array inside of a struct from within a function?
body: <p>I am trying to rewrite a bit array thingy I wrote, and one of the thing i wanted to add is a function that makes it easy to set the values in a bit array. right now, my bit array looks like this:</p>
  
  <pre><code>typedef struct{
    int length;
    char bitarray[];
  }BitArray;
  </code></pre>
  
  <p>I am trying to write a function:</p>
  
  <pre><code>void initBitArray(BitArray * b, int numBits, int initVal);
  </code></pre>
  
  <p>That set length to numBits and bitarray to an array of chars that is numBits/8 + 1 long, with each char having a value initVal. The only part I am having trouble with is with setting the value of bitarray. This isn't homework or anything, I was just trying to make some hobby code prettier.
  This is what I tried to do:</p>
  
  <pre><code>void initBitArray(BitArray * b, int numBits, int initVal){
    char foo[numBits/8 + 1]; 
    b-&gt;bitarray = foo;
    int i;
    for (i=0; i&lt;numBits/8 + 1; ++i){
      b-&gt;bitarray[i]=val;
    }
    b-&gt;length = numBits;
    return;
  }
  </code></pre>
  
  <p>Obviously this doesn't work :p</p>
  
  <p>I tried this:</p>
  
  <pre><code>void initBitArray(BitArray * b, int numBits, int initVal){
    b = (BitArray *)realloc( b, sizeof(b) + numBits/8 + 1);
    b-&gt;length = numBits;
    int i;
    for (i=0; i&lt; (b-&gt;length); ++i){
      b-&gt;bitarray[i]=initVal;
    }
    return;
  }
  </code></pre>
  
  <p>and it compiles but gives me a runtime error?</p>
  
  <pre><code>*** glibc detected *** ./prog: realloc(): invalid old size: 0xbfe573f0 ***
  ======= Backtrace: =========
  /lib/libc.so.6[0xb76c0fd4]
  /lib/libc.so.6[0xb76c4a29]
  /lib/libc.so.6(realloc+0x107)[0xb76c5657]
  /lib/libc.so.6(realloc+0x3c)[0xb76c558c]
  ./prog[0x8048556]
  ./prog[0x80483f1]
  ======= Memory map: ========
  </code></pre>