很多人知道用 strncpy 取代 strcpy 來避免緩衝區溢位,但若同時考慮執行效率,strlcpy 往往是更好的選擇。
char *strcpy(char *to, const char *from)
{
char *save = to;
for (; (*to = *from) != '\0'; ++from, ++to);
return save;
}
它依 \0 判斷結束,若目標空間不足就會造成 buffer overflow。而實務上 from 往往來自使用者輸入,可能是一段非常長的字串,因此 strcpy 並不安全。
char *strncpy(char *s1, const char *s2, size_t n);
標準規定 n 並不是 sizeof(s1),而是「要複製的字元個數」,而且有兩個容易踩到的問題:
其一,它不保證以 \0 結束:
char buf[8]; strncpy(buf, "abcdefgh", 8); /* buf 被填滿,卻沒有結束符 */
其二,若來源較短而 n 較大,它會把剩下的空間全部填成 \0,造成效率浪費:
char buf[80]; strncpy(buf, "abcdefgh", 79); /* 實際寫入 79 個位元組 */
因此標準寫法必須自己補上結束符:
strncpy(path, src, sizeof(path) - 1); path[sizeof(path) - 1] = '\0'; len = strlen(path);
/* 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);
使用它不必手動處理 \0,只要把 sizeof(dst) 告知即可:
strlcpy(path, src, sizeof(path));
len = strlen(path);
if (len >= sizeof(path))
printf("src is truncated.");
因為它回傳 strlen(src),我們也能很方便地判斷資料是否被截斷。
strlcpy 並不屬於 ANSI C,至今仍未標準化。它源自 OpenBSD 2.4,之後許多 Unix-like 系統的 libc 都加入了這個函式,FreeBSD 與 glibc 都有提供,因此多數 Linux 發行版都能使用。但 Windows 環境沒有 strlcpy,需以 strncpy 搭配 memset 或 Platform Safety Library 的替代方案來處理。