title: Why am I getting a double free or corruption error with realloc()?
body: <p>I've tried to write a string replace function in C, which works on a <code>char *</code>, which has been allocated using <code>malloc()</code>.  It's a little different in that it will find and replace strings, rather than characters in the starting string.</p>
  
  <p>It's trivial to do if the search and replace strings are the same length (or the replace string is shorter than the search string), since I have enough space allocated.  If I try to use <code>realloc()</code>, I get an error that tells me I am doing a double free - which I don't see how I am, since I am only using <code>realloc()</code>.</p>
  
  <p>Perhaps a little code will help:</p>
  
  <pre><code>void strrep(char *input, char *search, char *replace) {
      int searchLen = strlen(search);
      int replaceLen = strlen(replace);
      int delta = replaceLen - searchLen;
      char *find = input;
  
      while (find = strstr(find, search)) {
  
          if (delta &gt; 0) {
              realloc(input, strlen(input) + delta);
              find = strstr(input, search);            
          }
  
          memmove(find + replaceLen, find + searchLen, strlen(input) - (find - input));
          memmove(find, replace, replaceLen);
      }
  }
  </code></pre>
  
  <p>The program works, until I try to <code>realloc()</code> in an instance where the replaced string will be longer than the initial string.  (It still kind of works, it just spits out errors as well as the result).</p>
  
  <p>If it helps, the calling code looks like:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;string.h&gt;
  #include &lt;stdlib.h&gt;
  
  void strrep(char *input, char *search, char *replace);
  
  int main(void) {
      char *input = malloc(81);
  
      while ((fgets(input, 81, stdin)) != NULL) {
          strrep(input, "Noel", "Christmas");
      }
  }
  </code></pre>