strncpy or strlcpy in my case

Viewed 36657

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.

6 Answers

You should always the standard function, which in this case is the C11 strcpy_s() function. Not strncpy(), as this is unsafe not guaranteeing zero termination. And not the OpenBSD-only strlcpy(), as it is also unsafe, and OpenBSD always comes up with it's own inventions, which usually don't make it into any standard.

See http://en.cppreference.com/w/c/string/byte/strcpy

The function strcpy_s is similar to the BSD function strlcpy, except that strlcpy truncates the source string to fit in the destination (which is a security risk)

  • strlcpy does not perform all the runtime checks that strcpy_s does
  • strlcpy does not make failures obvious by setting the destination to a null string or calling a handler if the call fails.
  • Although strcpy_s prohibits truncation due to potential security risks, it's possible to truncate a string using bounds-checked strncpy_s instead.

If your C library doesn't have strcpy_s, use the safec lib. https://rurban.github.io/safeclib/doc/safec-3.1/df/d8e/strcpy__s_8c.html

Related