strncpy
is never the right answer when your destination string is zero-terminated. strncpy
is a function intended to be used with non-terminated fixed-width strings. More precisely, its purpose is to convert a zero-terminated string to a non-terminated fixed-width string (by copying). In other words, strncpy
is not meaningfully applicable here.
The real choice you have here is between strlcpy
and plain strcpy
.
When you want to perform "safe" (i.e. potentially truncated) copying to dst_arr
, the proper function to use is strlcpy
.
As for dst_ptr
... There's no such thing as "copy to dst_ptr
". You can copy to memory pointed by dst_ptr
, but first you have to make sure it points somewhere and allocate that memory. There are many different ways to do it.
For example, you can just make dst_ptr
to point to dst_arr
, in which case the answer is the same as in the previous case - strlcpy
.
Or you can allocate the memory using malloc
. If the amount of memory you allocated is guaranteed to be enough for the string (i.e. at least strlen(src_str) + 1
bytes is allocated), then you can use the plain strcpy
or even memcpy
to copy the string. There's no need and no reason to use strlcpy
in this case , although some people might prefer using it, since it somehow gives them the feeling of extra safety.
If you intentionally allocate less memory (i.e. you want your string to get truncated), then strlcpy
becomes the right function to use.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…