title: What is the source of this 'realloc(): invalid next size' error
body: <p>I've read the other questions of this type, but I still can't figure out why this error is occurring in my code.</p>
  
  <p>Here is my code:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  typedef struct {                 
      int len;
      int str[0];
  } bit_str;
  
  bit_str * input(void);
  void print_bitstr(bit_str * s);
  
  int main(void)
  {
      bit_str * s1 = input();
      print_bitstr(s1);
  
      return 0;
  }
  
  bit_str * input(void)
  {
      bit_str *s = (bit_str *) malloc(sizeof(bit_str)); 
      int count = 0, bit;
  
      while ((bit = getchar()) != 'k'){
          s = (bit_str *) realloc(s, sizeof(*s) + sizeof(int));           
          s-&gt;str[count++] = bit - 48;
      }
  
      s-&gt;len = count;
      return s;
  }
  
  void print_bitstr(bit_str * s)
  {
      for (int i = 0; i &lt; s-&gt;len; i++)
          printf("%d ", s-&gt;str[i]);
      printf("\n");
  
      return;
  }
  </code></pre>
  
  <p>This code is part of a program I was trying to add two bit strings together (as an exercise from a Data Structures book). </p>
  
  <p>I've created a struct that will store the bits string and it's length. The struct is initialized using a malloc in the input function. It is reallocated every time a new bit is added. The bits are read using a getchar, and the end of a bitstring is demarcated by the letter 'k'. </p>
  
  <p>When I compile the code, it works perfectly for exactly 6 bits. But if I try to input 7 bits, it crashes with following error:  </p>
  
  <pre><code>&gt; realloc(): invalid next size  
  </code></pre>
  
  <p>I've read the other posts with similar error, but I couldn't figure out why this error is occurring in my code here. I've made sure that when I reallocate, I use sizeof operator to get the size, instead of absolute values. </p>
  
  <p>Can someone please help me figure out what I'm doing wrong here?</p>