title: Allocating memory for a char array to concatenate a known piece of text and an integer
body: <p>I want to concatenate a piece of text, for example "The answer is " with a signed integer, to give the output "The number is 42".</p>
  
  <p>I know how long the piece of text is (14 characters) but I don't know how many characters the string representation of the number will be.</p>
  
  <p>I assume the worst case scenario, the largest signed 16-bit integer has 5 digits, plus one extra in case it is negative, so is the following code the correct way to do it?</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  int main()
  {
      char *message;
  
      message = malloc(14*sizeof(char)+(sizeof(int)*5)+1);
  
      sprintf(message, "The answer is %d", 42);
  
      puts(message);
  
      free(message);
  }
  </code></pre>