title: glibc detected: realloc(): invalid next size
body: <p>I'm trying to create a dynamic array which stores the words of a given sentence in a dynamic 2-D array using a double pointer, but whenever I give more than three words, I get the following error:</p>
  
  <p><code>*** glibc detected *** ./a.out: realloc(): invalid next size: 0x000000000255a030 ***</code></p>
  
  <p>Relevant code below:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;  
  int main()  
  {
      char **ptr=NULL;  
      char letter;    
      int ptrsize=1, wordsize=1;  
      ptr=malloc(ptrsize*sizeof(char *));
      ptr[ptrsize]=(char *)malloc(wordsize*sizeof(char));
      do
      {
              letter=getchar();
              while ((letter!=' ')&amp;&amp;(letter!='\n'))
              {
                      ptr[ptrsize][wordsize]=letter;
                      *ptr= realloc(*ptr,wordsize+1);
                      wordsize++;
                      letter=getchar();
              }
              ptrsize++;
              ptr = realloc(ptr,ptrsize*sizeof(char));
              wordsize=1;
              ptr[ptrsize]=malloc(wordsize*sizeof(char));
      }
      while (letter!='\n');
      return 0;
  }
  </code></pre>
  
  <p>I have managed to increase the size of the sentence by making alterations to the malloc and realloc of the double pointer, but still haven't found any solid solution. Thanks in advance.</p>