title: How to declare appropriate size for the buffer
body: <p>I'm using <code>TCHAR</code> in the Visual C++ poject I'm working on, which definition is shown below:</p>
  
  <pre><code>#ifdef _UNICODE
      typedef wchar_t TCHAR;
  #else
      typedef char TCHAR;
  #endif
  </code></pre>
  
  <p>I need to put some data into buffer <code>buff</code>:</p>
  
  <pre><code>char buff[size] = {0};  // how to declare the buffer size - what should be its value ?
  sprintf(buff, "%s (ID: %i)", res-&gt;name(), res-&gt;id());
  </code></pre>
  
  <p>where:</p>
  
  <p><code>name()</code> returns <code>TCHAR*</code></p>
  
  <p><code>id()</code> returns <code>int</code></p>
  
  <p>How to calculate the value of <code>size</code> - exact buffer capacity for actual needs (smaller if no unicode is defined, bigger if unicode is defined) ? In addition I'd like to protect myself from buffer overflow possibility, what kind of protection should I use ?</p>
  
  <p>What's more, I've declared here the buffer as <code>char</code>. If I declare the buffer as <code>int</code>, would it be any difference for the size value (i.e 4 times smaller if compared to declared as char) ?</p>
  
  <p><strong>UPDATE</strong></p>
  
  <p>What I come up with partially based on Mats Petersson answer is:</p>
  
  <pre><code>    size_t len;
      const char *FORMAT;
  #ifndef _UNICODE
      len = strlen((char*)res-&gt;name()); 
      FORMAT = "%s (ID: %i)";
  #else
      len = wcslen(res-&gt;name());
      FORMAT = "%S (ID: %i)";
  #endif    
  
      int size = 7 * sizeof(TCHAR) +                             /* place for characters inside format string */
                 len * sizeof(TCHAR) +                           /* place for "name" characters */
                 strlen(_itoa(id, ioatmp, 10)) * sizeof(TCHAR) + /* place for "id" digits */
                 1 * sizeof(TCHAR);                              /* zero byte(s) string terminator */
  
      char *buff = new char[size];  /* buffer has to be declared dynamically on the heap,
                                     * because its exact size is not known at compilation time */
      sprintf(buff, FORMAT, name, id);
      delete[] buff;
  </code></pre>
  
  <p>Is it correct thinking or did I miss something ?</p>