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

时间:2016-02-27 04:15:57

标签: c++ core fault

#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 ++,需要一些帮助,以便我不断收到Segmentation fault(core dumped)错误。一切都按照我想要的方式运行但运行后我得到Segmentation故障(核心转储)

1 个答案:

答案 0 :(得分:0)

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