c++ 分段错误(核心转储)错误[重复]

问题描述 投票:0回答:1
#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++ 有点陌生,需要一些帮助来解释为什么我不断收到分段错误(核心转储)错误。一切正常,我想要它,但运行后我得到分段错误(核心转储)

c++ segmentation-fault
1个回答
1
投票

您不会从

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

© www.soinside.com 2019 - 2024. All rights reserved.