gpt4 book ai didi

c - 为什么 strcpy 在 C 中不安全?

转载 作者:太空狗 更新时间:2023-10-29 14:54:59 24 4
gpt4 key购买 nike

<分区>

我是初学者,正在学习如何用 C 语言复制字符串。

这是我刚遇到的一个问题:

每次我尝试使用“strcpy”命令将字符串 1 复制到字符串 2 时,Visual Studio 2013 都会给我一条错误/警告消息,指出“strcpy”不安全,并建议我改用 strcpy_s。

您能解释一下为什么 strcpy 使用不安全吗?什么是 strcpy 更安全的替代品?

这是我的代码:

#include<stdio.h>
#include<string.h>
main()
{
char str1[] = "Copy a string.";
char str2[15];
char str3[15];
int i;

/* with strcpy() */
strcpy(str2, str1);
/* Without strcpy() */
for (i = 0; str1[i]; i++)
str3[i] = str1[i];
str3[i] = '\0';
/* Display str2 and str3 */
printf("The content of str2: %s\n", str2);
printf("The content of str3: %s\n", str3);
return 0;
}

附言我在 Windows 7 64 位旗舰版上使用 Visual Studio 2013 64 位旗舰版。感谢您的宝贵时间!

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com