您必须使用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