title: Concatenating a char array in C: dynamically handling memory
body: <p>I'm confused on what I'm doing wrong in my C program: I'm trying to create a string that begins with a <code>'!'</code> and adds 6 values read from a sensor (separated by commas) and then sends it over a serial port. A sample output would be: <code>"!5,5,5,5,5,5"</code> or <code>"!34,34,34,34,34,34"</code>.</p>
  
  <p>The problem: Because the sensor values (5 or 34 in the example above) can range from 0 to 255, I don't know at runtime how big my char array needs to be. This means I have to dynamically reallocate memory every time I want to add to my string. Below is my attempt to do so, but I'm doing this wrong because I see nothing coming across my serial port (indicating that there's a runtime error).</p>
  
  <p><strong>How can I properly implement code to allocate memory dynamically for a string?</strong> My attempts to use <code>malloc</code> and <code>realloc</code> aren't behaving as expected.</p>
  
  <pre><code>char* convertIntToString(uint8_t integerValue){
      char *str = malloc(4);          //up to 3 digits + 1 for null termination 
      utoa(integerValue, str, 10);
      return str;
  }
  
  char* concat(char *s1, char *s2)
  {
      char *result = malloc(strlen(s1)+strlen(s2)+1);//+1 for the zero-terminator
      //in real code you would check for errors in malloc here
      strcpy(result, s1);
      strcat(result, s2);
      return result;
  }
  
  int main(void)
  {
      uint8_t analogValue;
      char *outputStr = malloc(1);  //initalize size of char array = 1 element
  
      while (1) {
          outputStr = realloc(outputStr, 1);
          outputStr = concat(outputStr, "!");
          analogValue = ReadADC(0);
          outputStr = concat(outputStr, convertIntToString(analogValue));
          for(int i = 0; i &lt; 5; i++){
              outputStr = concat(outputStr, ",");
              outputStr = concat(outputStr, convertIntToString(analogValue));
          }
          CDC_Device_SendString(&amp;VirtualSerial_CDC_Interface, outputStr); //send string via USB
          free(outputStr);
      }  
  }
  </code></pre>