strncpy or strlcpy in my case

hari picture hari · Aug 8, 2011 · Viewed 29.5k times · Source

what should I use when I want to copy src_str to dst_arr and why?

char dst_arr[10];
char *src_str = "hello";

PS: my head is spinning faster than the disk of my computer after reading a lot of things on how good or bad is strncpy and strlcpy.

Note: I know strlcpy is not available everywhere. That is not the concern here.

Answer

AnT picture AnT · Aug 8, 2011

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.