c++ 分段错误(核心转储)错误

c++ Segmentation fault (core dumped) error

本文关键字:错误 转储 核心 分段 c++      更新时间:2023-10-16
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
string swapLastName(const string full_name, const string new_last_name)
{
string firstname;
string newname;
istringstream StrStream(full_name);
// seperate first name from full name
StrStream >> firstname;
// combines first name with new last name
newname=firstname +' '+ new_last_name;
// outputs new name
cout << "Your new name: " << newname << endl;
}
int main()
{
string full_name;
string new_last_name;
//input full name
cout << "Type your full name: ";
//getline to get entire full name
getline(cin, full_name);
//input new last name
cout << "Enter your new last name: ";
getline(cin, new_last_name);
swapLastName(full_name, new_last_name);
return 0;
}

对 c++ 有点陌生,需要一些帮助来解释为什么我不断收到分段错误(核心转储)错误。一切都可以正常工作,我想要它,但在它运行后我得到分段错误(核心转储)

你不从swapLastName返回任何内容,但你给它一个返回类型string。当控件到达函数的末尾时,它没有返回string,因此它最终会得到一个string大小的垃圾内存块。string析构函数在临时字段被销毁时运行,并且由于所有内部字段都未初始化且毫无意义,因此它可能会在尝试释放某个随机地址时出现段错误。