引用字符串参数导致Segmentation错误
Reference string parameter causes Segmentation fault?
在代码::块上使用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);
}
相关文章:
- 示例外壳应用程序显示的 V8 "segmentation fault (core dumped)"错误
- 给定一个整数数组,需要在Max_Heap上运行操作。得到错误"segmentation fault",有什么想法吗?(C++)
- 导致Segmentation错误的结构中的矢量
- OpenGL "Segmentation fault"错误
- 如何修复访问动态数组中结构中的字符串变量时"segmentation fault (core dumped)"错误
- 如何修复 C++ 中的'Segmentation fault'错误
- 尝试读取包含 ints 并存储在 int vector 中的文件,但我不断收到错误"Segmentation fault (core dumped)"
- 为什么当我更改此代码时会给我"segmentation fault"错误?
- 尝试将文本文件加载到动态分配的 2D 数组中时出现'Segmentation fault'错误
- 由于while循环中的条件,导致Segmentation错误
- 取消引用会导致Segmentation错误
- 调用构造函数定义中的函数后收到Segmentation Fault 11错误
- 为什么我在运行程序时收到错误"segmentation fault"?
- 当我尝试从结构列表中访问内存时出现错误:" Program received signal SIGSEGV, Segmentation fault."
- 当g++静态链接pthread时,导致Segmentation错误,原因何在
- 为什么我的程序在运行后给出"segmentation fault"(核心转储)错误
- 在Qt错误显示:"Fault Module Name: Qt5Cored.dll"在win 7和调试时:"segmentation fault"在CentOS Linux和Win 7中
- 引用字符串参数导致Segmentation错误
- 为什么 g++ 在将节点指向数据字符时返回'Segmentation fault'错误?
- JNI从c调用java会出现Segmentation错误(核心转储)