解释#
这样的漏洞在 2023 年 CWE 已知被利用漏洞排行 中排在第 3 位, 因此我们需要有手段避免它. C11 于是允许实现提供这些函数的安全版本, 其要求给出长度参数, 而 Visual Studio 将它拓展到了 C++ 上:
strcpy#
1char* strcpy(char* 拷贝目的地, char const* 源字符串);
2
3char const* input = "hello world";
4char result[100];
5strcpy(result, input);
strcpy_s#
1/*略*/ strcpy_s(char* 拷贝目的地, /*略*/ 拷贝目的地的最大长度, char const* 源字符串);
2
3char const* input = "hello world";
4char result[100];
5strcpy_s(result, 100, input);
通过 #define _CRT_SECURE_NO_DEPRECATE, 我们将能强行使用 strcpy.
错误
strcpy_s 的目的是为了限制字符串拷贝的长度, 防止黑客传入的几亿长度的字符串也会被完全拷贝, 所以你不应该像下面这样写代码:
1char const* input = "this is a very long string";
2char result[5];
3strcpy_s(result, strlen(input), input); // strlen(input) 是最大的拷贝长度, 那 strcpy_s 的意义何在?!
这样的写法和直接用 strcpy(result, input) 没有区别.