引用字符串参数导致Segmentation错误

Reference string parameter causes Segmentation fault?

本文关键字:Segmentation 错误 字符串 参数 引用      更新时间:2023-10-16

在代码::块上使用GCC编译器,我得到一个错误:

Segmentation fault (core dumped)
Process returned 139 (0x8B)
...

输入要求的输入后。这是我的测试程序:

#include <iostream>
#include <string>
using namespace std;
string getInput(string &input, string prompt)
{
    cout << prompt;
    getline(cin, input);
}
int main()
{
    string input;
    getInput(input, "What's your name?n>");
    cout << "Hello " << input << "!" << endl;
    return 0;
}

我做错了什么?参考参数使用不正确吗?

函数getInput被声明为返回string,但没有return语句,这是未定义的行为。如果你这样更改声明:
void getInput(string &input, string prompt)

分段错误应该消失。打开警告可以帮助您发现这个问题,使用gcc -W -Wall -pedantic,我会收到以下带有原始代码的警告:

warning: no return statement in function returning non-void [-Wreturn-type]
函数getInput表示它返回一个string,调用代码试图复制它。但是在getInput函数中没有return。由于复制一个实际上没有返回的返回值是未定义的行为,"任何事情"都可能在此时发生——在这种情况下,结果似乎是segfault。

由于使用input作为引用,因此不需要返回字符串。只需将函数原型更改为void即可。

如果在编译时启用警告,您将更容易看到此类错误。

 string getInput(string &input, string prompt)
 {
    cout << prompt;
    getline(cin, input);
 }  

您声明函数返回string类型,但函数中没有return语句。当流到达该函数的末尾时,它将导致未定义的行为。

尝试:

 void getInput(string &input, string prompt)
 {
    cout << prompt;
    getline(cin, input);
 }
相关文章: