关于strcpy() strncpy()运用警告的疑问?
//cow.h
#ifndef COW_H_
#define COW_H_
class Cow
{
private:
enum {Max = 20};
char name[Max];
char *hobby;
double weight;
public:
Cow();
Cow(const char *nm, const char *ho, double wt);
Cow(const Cow &c);
~Cow();
Cow & operator= (const Cow &c);
void ShowCow()const;
};
#endif
//cow.cpp
#include "cow.h"
#include <iostream>
#include <cstring>
using std::cout;
using std::endl;
Cow::Cow()
{
strcpy(name, "none");
hobby = new char[1];
hobby[0] = '\0';
weight = 0.0;
}
Cow::Cow(const char *nm, const char *ho, double wt)
{
if(strlen(nm) < 20){
strcpy(name, "none");
}
else{
strncpy(name, nm, 20);
name[19] = '\0';
}
hobby = new char[strlen(ho) + 1];
strcpy(hobby, ho);
weight = wt;
}
Cow::Cow(const Cow &c)
{
strcpy(name, c.name);
hobby = new char[strlen(c.hobby) + 1];
strcpy(hobby, c.hobby);
weight = c.weight;
}
Cow::~Cow()
{
delete [] hobby;
}
Cow & Cow::operator= (const Cow &c)
{
if(this == &c)
return *this;
delete [] hobby;
strcpy(name, c.name);
hobby = new char[strlen(c.hobby) + 1];
strcpy(hobby, c.hobby);
weight = c.weight;
return *this;
}
void Cow::ShowCow()const
{
cout << "Name: " << name << endl;
cout << "Hobby: " << hobby << endl;
cout << "Weight: " << weight <, endl;
}
出现警告:
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.
将strcpy -> strcpy_s 后又出现strncpy的警告,
囧啊!
疑问如下:谷歌查了原因是怕出现溢出错误,所以警告。
但是我对是否溢出做出了处理啊,看红色代码处。
看绿色代码处,以前动态字符串变量都是这样弄的,咋今天这样弄了就出警告了,
难道今天运气不行么= =
求前辈指点一二
[解决办法]
C运行库函数本来就不安全,你直接在include stdio.h的前面加上_CRT_SECURE_NO_WARNINGS就行了
M$希望你用它专有的函数,其用心不良