title: C: Realloc issues with double pointer
body: <p>I am trying to copy a <code>char word[50]</code> array to a <code>char **wordlist</code> double pointer and then <code>realloc(wordlist, (numwords+1)*sizeof(char*))</code> to increase the size of word list by one more <code>char*</code> to hold the next <code>word</code>.</p>
  
  <p>I keep getting a <code>*** glibc detected *** ./program: realloc(): invalid next size</code> error</p>
  
  <p>I am declaring it as <code>wordlist = realloc(wordlist, (numwords+1)*sizeof(char*))</code></p>
  
  <pre><code>void outFile(char *argv[], char **wordlist)
    {
        if((inFilePtr = fopen(argv[2], "r")) != NULL)
        {
            if((outFilePtr = fopen(endOfFile, "w")) != NULL)
            {
                while((c = fgetc(inFilePtr)) != EOF)
                {
                    if(!(isspace(c)))
                    {
                        word[wordIndex] = c;
                        wordIndex++;
                        rowLim++;
                    }
                    if(isspace(c))
                    {
                        wordIndex = 0;
                        if(rowLim &lt; limit)
                        {
                            rowLim++;
                            strcat(text[rowNum], word);
                            strcat(text[rowNum], " \0");
                            wordlist[numwords] = strdup(word);
                            /*strcat(wordlist[numwords], "\n\0");*/
                            memset(word, 0, 50);
                            prev = rowLim;
                            wordlist = realloc(wordlist, (numwords + 1)*sizeof(char*));
                            numwords++;
                        }
                        else
                        {
                            strcat(text[rowNum], "\n\0");
                            printf("text[%d] = %s",rowNum, text[rowNum]);
                            fputs(text[rowNum], outFilePtr);
                            rowNum++;
                            strcat(text[rowNum], word);
                            strcat(text[rowNum], " \0");
                            /*strcat(wordlist[numwords], word);
                            strcat(wordlist[numwords], "\n\0");
                            wordlist = realloc(wordlist, (numwords + 1)*sizeof(char*));*/
                           numwords++;
                           memset(word, 0, 50);
                           rowLim = rowLim - prev;
                       }
                       wordIndex = 0;
                   }
               }
               strcat(text[rowNum], "\n\0");
               printf("text[%d] = %s",rowNum, text[rowNum]);
               fputs(text[rowNum], outFilePtr);
               fclose(outFilePtr);
           }
  </code></pre>