您的位置:首页 > Web前端

strcpy' this function or variable may be unsafe. consider using strcpy_s instead

2015-01-06 12:35 363 查看
The function strcpy is considered unsafe due to the fact that there is no bounds checking and can lead to buffer overflow.

Consequently, as it suggests in the error description, you can use strcpy_s instead of strcpy:

Solution 1:

strcpy_s( char *strDestination, size_t numberOfElements, const char *strSource );

Attention: numberOfElements is the size of strDestination.

Solution 2:

A quick fix is to add the _CRT_SECURE_NO_WARNINGS definition to your project's settings

Right-click your C++ and chose the "Properties" item to get to the properties window.

Now follow and expand to, "Configuration Properties"->"C/C++"->"Preprocessor"->"Preprocessor definitions".

In the "Preprocessor definitions" add

_CRT_SECURE_NO_WARNINGS

but it would be a good idea to add

_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)

as to inherit predefined definitions

For these two solution,
the first one is highly recommended
. For the second, the compiler may not detect errors about stack.

#include<iostream>
#include<string>
using namespace std;

int main(){
	char *s1 = "Hello";
	char *s2 = "World";
	
	size_t t = strlen(s1) + strlen(s2);
	char *s = new char[t + 1];
	//strcpy(s, s1);
	strcpy_s(s, strlen(s1)+1, s1);
	cout << s << endl;

	strcat_s(s,strlen(s)+strlen(s2)+1, s2);
	cout << s << endl;
	delete[]s;
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐