【问题标题】:c++ Segmentation fault (core dumped) errorc ++分段错误(核心转储)错误
【发布时间】:2016-02-27 04:15:57
【问题描述】:
#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 中返回一个字符串
  • @NickLamp clang 显然会编译这个并发出警告。那些杂烩。

标签: c++ core fault


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2021-10-19
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 2017-02-25
    • 2016-07-12
    • 2018-03-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多