使用字符数组操作strcpy()和字符串操作string.c_str()时出现错误,显示SIGNAL: SIGSEGV。
使用
strcpy(s1, s2)函数可以复制字符串s2到字符串s1。
string.c_str()返回当前字符串的首字符地址
原代码
#include <bits/stdc++.h>
#include <iostream>
#include <string>
using namespace std;
#pragma warning(disable:4996)
int main() {
char arr[8];
string s = "LaoWang";
strcpy(arr, s.c_str());
cout << arr << endl;
}
VS报错
错误 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()作为替代
解决方案:
-
使用
strcpy_s() -
在头文件中添加
#pragma warning(disable:4996)
在C++编程中,尝试使用strcpy()函数复制字符串s到字符数组arr时,如果未确保目标数组足够大,会导致SIGSEGV错误。微软推荐使用更安全的strcpy_s()代替。另外,s.c_str()用于获取string对象的C风格字符串,但直接用于strcpy()可能导致内存问题。为避免错误,可以考虑使用std::copy()或std::strcpy_s()进行安全复制。
2228

被折叠的 条评论
为什么被折叠?



