VS2013 strcpy 报错的3种处理方法

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. //C++中使用strcpy的问题:  
  2. #include<iostream>  
  3. #include<cstring>  
  4. using namespace std;  
  5. class Student{  
  6. public:  
  7.     Student(char *name1, char *stu_no1, float score1);  
  8.     ~Student();  
  9.     void disp();  
  10. private:  
  11.     char *name;  
  12.     char *stu_no;  
  13.     float score;  
  14. };  
  15. Student::Student(char *name1, char *stu_no1, float score1){  
  16.     name = new char[strlen(name1) + 1];  
  17.     strcpy(name, name1);  
  18.     stu_no = new char[strlen(stu_no1) + 1];  
  19.     strcpy(stu_no, stu_no1);  
  20.     score = score1;  
  21. }  
  22. Student::~Student(){  
  23.     delete []name;  
  24.     delete []stu_no;  
  25. }  
  26. void Student::disp(){  
  27.     cout << "name: " << name << endl;  
  28.     cout << "stu_no: " << stu_no << endl;  
  29.     cout << "score: " << score << endl;  
  30. }  
  31. int main(){  
  32.     Student stu1("Li ming""20080201", 90);  
  33.     stu1.disp();  
  34.     Student stu2("Wang fang""20080202", 85);  
  35.     stu2.disp();  
  36.     return 0;  
  37. }  

报错: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定义:

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. errno_t __cdecl strcpy_s(_Out_writes_z_(_SizeInBytes) char * _Dst, _In_ rsize_t _SizeInBytes, _In_z_ const char * _Src);  

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

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

本例中,修改代码为:

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. Student::Student(char *name1, char *stu_no1, float score1){  
  2.     name = new char[strlen(name1) + 1];  
  3.     <strong>strcpy_s(name, strlen(name1) + 1, name1);</strong>  
  4.     stu_no = new char[strlen(stu_no1) + 1];  
  5.     <strong>strcpy_s(stu_no, strlen(stu_no1) + 1, stu_no1);</strong>  
  6.     score = score1;  
  7. }  
即可。

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

或者 在源程序一开始 加上

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. #pragma warning(disable : 4996)  
  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值