My favourite C string function is snprintf:<p>• It takes a buffer size and truncates the output to the buffer size if it's too large.<p>• The buffer size includes the null terminator, so the simplest pattern of snprintf(buf, sizeof(buf), …) is correct.<p>• It always null-terminates the output for you, even if truncated.<p>• By providing NULL as the buffer argument, it will tell you the buffer size you need if you want to dynamically allocate.<p>And of course, it can safely copy strings:<p><pre><code> snprintf(dst_buf, sizeof(dst_buf), "%s", src_str);
</code></pre>
Including non-null-terminated ones:<p><pre><code> snprintf(dst_buf, sizeof(dst_buf), "%.*s", (int)src_str_len, src_str_data);
</code></pre>
And it's standard and portable, unlike e.g. strlcpy. It's one of the best C99 additions.