之所以说strcpy_s比strcpy安全是因为strcpy需要程序员去保证输出buffer不会越界。
strcpy正常案例
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char a[5];
char b[4]="abc";
strcpy(a,b);
cout<<a<<endl;
return 0;
}
执行结果:
strcpy越界案例
#include <iostream>
#include <string.h>
#include <vector>
using namespace std;
int main()
{
char a[2];
char b[5]="abcd";
strcpy(a,b);
cout<<a<<endl;
cout<<a[3]<<endl;//数组不检查越界
cout<<(a+3)<<endl;
cout<<*(a+3)<<endl;
cout<<sizeof(a);
return 0;
}
执行结果:
sizeof(a)==2;但是数组访问a[3]却有数值。
cout<<a[3]<<endl;//数组不检查越界
cout<<(a+3)<<endl;
cout<<*(a+3)<<endl;
strcpy_s的使用
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
char s[3];
char s1[6] = "abcd";
strcpy_s(s,s1);
cout << s;
system("pause");
return 0;
}
执行结果:
当将strcpy_s(s, s1);修改为strcpy_s(s, 6,s1);时,执行结果:
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
char s[3];
char s1[6] = "abcde";
cout << sizeof(s) << endl;
strcpy_s(s, 7, s1);
cout << s << endl;
cout << sizeof(s) << endl;
cout << s[4] << endl;
cout << (s + 4) << endl;
cout << *(s + 4) << endl;
system("pause");
return 0;
}
执行结果: