title: Convert built-in data type to std::string: memcpy vs snprintf
body: <p>I have referred to the <a href="https://stackoverflow.com/questions/5590381/easiest-way-to-convert-int-to-string-in-c">relevant question</a> and other posts before this. I am also aware that <code>std::to_string()</code> is the best way (but it's not available in few platforms).</p>
  
  <p>While <strong>experimenting</strong>, I came across a weird issue with <code>memcpy()</code>. For the example sake, assume that we always pass built-in data types (<code>int</code>, <code>char</code>, <code>long</code>) to below function:</p>
  
  <pre><code>template&lt;typename T&gt;
  std::string to_string (const T&amp; value)
  {
    std::string s(16, 0); // Max size captured
    ::memcpy(&amp;s[0], &amp;value, sizeof(value));
    return s;
  }
  </code></pre>
  
  <p>Running this function individually in a sample program works fine. But while plugging into a bigger code base, somehow it gives weird results! i.e. it gives spurious values. (Ubuntu 14.10, g++4.9 -std=c++11)</p>
  
  <p>However, if I convert the above program using <code>sprintf()</code>, it works fine.</p>
  
  <pre><code>template&lt;typename T&gt;
  std::string to_string (const T&amp; value)
  {
    std::string s(16, 0); // Max size captured
    s[::snprintf(&amp;s[0], "%d", value)] = 0;
    return s;
  }
  </code></pre>
  
  <p><strong>Question</strong>:  </p>
  
  <ol>
  <li>Am I touching undefined behavior with <code>memcpy()</code> (or even
  <code>sprintf()</code>)?</li>
  <li>Would byte ordering influence this code?</li>
  </ol>