关于Visual Studio 2013中strcpy函数的使用报错

本文探讨了在C++中使用strcpy时遇到的警告及其解决方法,详细介绍了strcpy_s函数的使用,以及如何禁用警告来提高代码安全性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//C++中使用strcpy的问题:
#include<iostream>
#include<cstring>
using namespace std;
class Student{
public:
	Student(char *name1, char *stu_no1, float score1);
	~Student();
	void disp();
private:
	char *name;
	char *stu_no;
	float score;
};
Student::Student(char *name1, char *stu_no1, float score1){
	name = new char[strlen(name1) + 1];
	strcpy(name, name1);
	stu_no = new char[strlen(stu_no1) + 1];
	strcpy(stu_no, stu_no1);
	score = score1;
}
Student::~Student(){
	delete []name;
	delete []stu_no;
}
void Student::disp(){
	cout << "name: " << name << endl;
	cout << "stu_no: " << stu_no << endl;
	cout << "score: " << score << endl;
}
int main(){
	Student stu1("Li ming", "20080201", 90);
	stu1.disp();
	Student stu2("Wang fang", "20080202", 85);
	stu2.disp();
	return 0;
}

报错:warning C4996: 'strcpy': This function or variable may be unsafe. Consider using strcpy_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.

解决:

1)根据warning,第一个方法,该strcpy为strcpy_s

strcpy_s定义:

errno_t __cdecl strcpy_s(_Out_writes_z_(_SizeInBytes) char * _Dst, _In_ rsize_t _SizeInBytes, _In_z_ const char * _Src);

注意strcpy_s中多了第二个参数,限制复制字符串的长度,避免越界。

微软的警告,主要因为那些C库的函数,很多函数内部是不进行参数检测的(包括越界类的),微软担心使用这些会造成内存异常,所以就改写了同样功能的函数,改写了的函数进行了参数的检测,使用这些新的函数会更安全和便捷。关于这些改写的函数你不用专门去记忆,因为编译器对于每个函数在给出警告时,都会告诉你相应的安全函数,查看警告信息就可以获知,在使用时也再查看一下MSDN详细了解。

本例中,修改代码为:

Student::Student(char *name1, char *stu_no1, float score1){
	name = new char[strlen(name1) + 1];
	strcpy_s(name, strlen(name1) + 1, name1);
	stu_no = new char[strlen(stu_no1) + 1];
	strcpy_s(stu_no, strlen(stu_no1) + 1, stu_no1);
	score = score1;
}
即可。

2)根据warning,第二个方法,To disable deprecation, us _CRT_SCURE_NO_WARNINGS. 找到项目--属性--配置属性--C/C++--命令行--其它选项 中填上【 /D "_CRT_SECURE_NO_DEPRECATE"】(注:中括号中的全部内容)。

或者 在源程序一开始 加上

#pragma warning(disable : 4996)

参考:http://blog.youkuaiyun.com/ycguhang/article/details/7170558

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值