您必須使用strcpy(如果您知道輸入的長度)或安全函數。
很多其他的答案也造成了同樣的錯誤,使得未終止的字符串成爲安全漏洞的主要來源。
正確的方法是使用安全的字符串拷貝功能,如StringCbCopy或推出自己的(雖然不夠健壯):
// Copy at most n-1 characters to dst, truncating if strlen(src) > n-1
// and guaranteeing NUL-termination.
void safe_strcpy(char *dst, const char *src, size_t n) {
strncpy(dst, src, n-1);
dst[n-1] = 0; // Guarantee NUL-termination.
}
然後如下
void f(const char *title, const char *author) {
BookType book;
safe_strcpy(book.title, title, sizeof book.title);
safe_strcpy(book.author, author, sizeof book.author);
}
哇,這是毫無意義的堅持認爲函數strncpy比strcpy的「更安全」的宗教信仰的極端的例子。或者可能是一個簡單的「思考o」。使用'sizeof(book.title)-1'作爲限制,或使用strlcpy:你的代碼在任何意義上都沒有「確保大小適合」:-) – 2010-04-17 12:48:13
你是對的。計數應該是'sizeof(book.title)-1'。另一方面,評論並不意味着代碼將確保,但用戶必須確保它在調用方法之前適合。 – 2010-04-17 12:56:54
'MIN(sizeof(book.title)-1,strlen(title)))'是不必要的。 http://stackoverflow.com/questions/2658182/how-to-use-char-as-char/2658217#2658217 – 2010-04-17 13:10:06