编辑:我添加了示例的源代码.
我遇到了这个例子:
char source[MAX] = "123456789";
char source1[MAX] = "123456789";
char destination[MAX] = "abcdefg";
char destination1[MAX] = "abcdefg";
char *return_string;
int index = 5;
/* This is how strcpy works */
printf("destination is originally = '%s'\n", destination);
return_string = strcpy(destination, source);
printf("after strcpy, dest becomes '%s'\n\n", destination);
/* This is how strncpy works */
printf( "destination1 is originally = '%s'\n", destination1 );
return_string = strncpy( destination1, source1, index );
printf( "After strncpy, destination1 becomes '%s'\n", destination1 );
Run Code Online (Sandbox Code Playgroud)
哪个产生了这个输出: …
据我所知,strlcpy和strlcat被设计为安全的替代品strncpy和strncat.然而,有些人仍然认为他们不安全,只是造成不同类型的问题.
有人可以举例说明如何使用strlcpy或strlcat(即一个总是 null终止其字符串的函数)会导致安全问题吗?
Ulrich Drepper和James Antill表示这是事实,但从未提供实例或澄清这一点.
我在VS2010中编写代码,我碰巧在编译后看到编译器为strcpy和sprintf调用提供了C4996警告("此函数或变量可能不安全").
但是,我无法获得memcpy的类似警告(可能在代码中有更多类似的'不安全'函数调用)
int _tmain(int argc, _TCHAR* argv[])
{
char buf1[100], buf2[100];
strcpy (buf1, buf2); // Warning C4996 displayed here asking to use strcpy_s instead
memcpy (buf1, buf2, 100); // No warning here asking to use memcpy_s
memcpy_s(buf1, 100, buf2, 100);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
为什么会这样?如何在代码中为所有可能的不安全呼叫打开C4996警告?