title: Memory allocation for simple variadic string concatenation in C
body: <p>I have the following test function to copy and concatenate a variable number of string arguments, allocating automatically:</p>
  
  <pre><code>char *copycat(char *first, ...) {
      va_list vl;
      va_start(vl, first);
      char *result = (char *) malloc(strlen(first) + 1);
      char *next;
      strcpy(result, first);
      while (next = va_arg(vl, char *)) {
          result = (char *) realloc(result, strlen(result) + strlen(next) + 1);
          strcat(result, next);
      }
      return result;
  }
  </code></pre>
  
  <p>Problem is, if I do this:</p>
  
  <pre><code>puts(copycat("herp", "derp", "hurr", "durr"));
  </code></pre>
  
  <p>it should print out a 16-byte string, <code>"herpderphurrdurr"</code>. Instead, it prints out a 42-byte string, which is the correct 16 bytes plus 26 more bytes of junk characters.</p>
  
  <p>I'm not quite sure why yet. Any ideas?</p>