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.
strncpyis never the right answer when your destination string is zero-terminated.strncpyis 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,strncpyis not meaningfully applicable here.The real choice you have here is between
strlcpyand plainstrcpy.When you want to perform “safe” (i.e. potentially truncated) copying to
dst_arr, the proper function to use isstrlcpy.As for
dst_ptr… There’s no such thing as “copy todst_ptr“. You can copy to memory pointed bydst_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_ptrto point todst_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 leaststrlen(src_str) + 1bytes is allocated), then you can use the plainstrcpyor evenmemcpyto copy the string. There’s no need and no reason to usestrlcpyin 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
strlcpybecomes the right function to use.