Difference between strncpy and snprintf?
strncpy
is not a bounded strcpy
. It's a fixed-length (not bounded, fixed-length) operation targeting a destination that's not a C string (null-terminated) but a null-padded field, like what was used in certain kinds of data record tables in the 70s and early 80s. It has basically no modern purpose and should not be used unless you really want this behavior.
snprintf
is the canonical C function for "bounded strcpy
". On POSIX systems, strnlen
+memcpy
would be another good alternative, and necessary if you need to support strings longer than INT_MAX
. If you don't have strnlen
, you can easily make it with memchr
and do the same.
Note that the simple use of snprintf
is not "bounded" in the sense of having a bound on how much it reads from the source; it necessarily reads the whole source string to determine the return value, which both can incur a time cost and depends on the source being a valid (terminated) string. If you want it bounded in the sense of both source and destination, you can do something like:
snprintf(dest, n, "%.*s", (int)n-1, src);
However, that's sufficiently non-idiomatic and error-prone that I would just use strnlen
and memcpy
instead.
Use snprintf(dst, n, "%s", src)
.
snprintf(dst, n, "%s", src)
makes certain that dst
is null character terminated. strncpy(dst, src, n)
does not do that.
strncpy(dst, src, n)
always does n
copies whereas snprintf(dst, n "%s", src)
does min(strlen(src),n)
copies