我只是使用MS'Visual Studio 2013学习c / c ++字符串,并找到有关函数strcpy_s的问题。 我发现即使一个人没有给出一个目标char *足够的内存,你也可以成功使用strcpy_s。有这样的风险吗?
代码:
const char* s5 = "hello!";
char* cs6 = new char[1];
strcpy_s(cs6, strlen(s5) + 1, s5);
cs6[2] = 'g';
string s7(cs6);
cout << "----------cs6------------" << endl;
cout << s7 << endl;
在控制台中显示:
----------cs6------------
heglo!
答案 0 :(得分:4)
并找到有关函数strcpy_s的问题。我发现即使一个人没有给目标char *足够的内存,你也可以成功使用strcpy_s。有任何风险......?
如果您正确使用strcpy_s
,请不要这样:
int buffer_size = 1; // this is silly since null terminated buffer
// of size 1 can only fit a string of length 0
char* cs6 = new char[buffer_size];
strcpy_s(cs6, buffer_size, s5);
cs6[buffer_size - 1] = '\0';
上面的代码非常安全。但是:
有这样的风险吗?
const char* s5 = "hello!"; char* cs6 = new char[1]; strcpy_s(cs6, strlen(s5) + 1, s5);
是的,存在风险。行为未定义。最佳案例场景:程序崩溃。更糟糕的情况:黑客黑客利用这种行为并窃取您受法律约束的数据,以免泄露。