strncpy or strlcpy in my case

前端 未结 6 1298
执笔经年
执笔经年 2020-12-10 11:21

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

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

P

6条回答
  •  猫巷女王i
    2020-12-10 11:31

    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

提交回复
热议问题