strcpy 函数遇到非标准字符串有溢出的风险,因此需要使用安全函数 strncpy 或 strlcpy
使用非标准函数 strlcpy 替换标准函数 strncpy 来提升字符串拷贝的效率。
strncpy
strncpy 为 ANSI C 标准函数,实现为
#include <string.h>
char *strcpy(char *dest, const char *src);
char *strncpy(char *dest, const char *src, size_t n);
但是 strncpy 不符合使用字符串使用习惯,不保证结尾为 \0
- 当
src大于dest时,没有\0 - 当
src小于dest时,剩余空间都会填\0,存在效率问题
strncpy 标准用法
strncpy(buf, str, buflen - 1);
if (buflen > 0)
buf[buflen - 1]= '\0';
strlcpy
strlcpy 并不属于 ANSI C,至今也还不是标准。
strlcpy 来源于 OpenBSD 2.4,之后很多 unix-like 系统的 libc 中都加入了 strlcpy 函数
// Copy src to string dst of size siz. At most siz-1 characters
// will be copied. Always NUL terminates (unless siz == 0).
// Returns strlen(src); if retval >= siz, truncation occurred.
size_t strlcpy(char *dst, const char *src, size_t siz);
使用 strlcpy 不用去手动负责 /0 了,仅需要把 sizeof(dst) 告之 strlcpy 即可
strlcpy(path, src, sizeof(path));
len = strlen(path);
if (len >= sizeof(path))
printf("src is truncated.");
并且 strlcpy 传回的是 strlen(str),因此我们也很方便的可以判断数据是否被截断