title: free(): double free detected in tcache 2 - c realloc error
body: <p>Im trying to save a file of words (max length 100 chars but I don't know how many), by storing pointers to the words in a char **. I start by allocating memory for 100 pointers and counting the words i save. If there are more then 100 words in the file i start reallocating memory with space for one more pointer every time i read a new word from file. Then i allocate space for the actual characters of the word.</p>
  
  <pre><code>    // init wordlist for 100 words
      char **mywords = malloc(100 * sizeof(char*));
      int wordcount = 0;
      char **word_pointer = mywords;
      while(!feof(wordlist))
      {
          // dynamically reallocate more memory if we have more than 100 words
          if (wordcount &gt;= 100) {
              realloc(mywords, sizeof(char*) * (wordcount+1));
          }
          char *new_word = *word_pointer;
          new_word = malloc(101 * sizeof(char));
          fgets(new_word, 101, wordlist);
          printf("%s", new_word);
          word_pointer++;
          wordcount++;
      }
  </code></pre>
  
  <p>I tested the code with a file of over 300 words and i get the error
  <code>free(): double free detected in tcache 2</code>
  I guess it's because of the malloc after the realloc? But I'm not sure how to fix it.</p>
  
  <p>EDIT</p>
  
  <p>I changed the loop to this:</p>
  
  <pre><code>// init wordlist for 100 words
      char **mywords = malloc(100 * sizeof(char*));
      int wordcount = 0;
      char **word_pointer = mywords;
      char *current_line = malloc(101 * sizeof(char));
      int max_length = 101;
  
      while(fgets(current_line, max_length, wordlist))
      {
          // dynamically reallocate more memory if we have more than 100 words
          if (wordcount &gt;= 100) {
              mywords = realloc(mywords, sizeof(char*) * (wordcount+1));
          }
          *word_pointer = current_line;
          word_pointer++;
          wordcount++;
      }
  </code></pre>
  
  <p>And it runs without errors. But my concern is that <code>word_pointer</code> will, after ever call of <code>realloc()</code> point to where the mywords list was before right? How do i change it so that after inserting e.g. 120 words, the realloc happens, that it points to the new mywords+120 so that i can keep inserting pointers?</p>