使用getline和字符串函数C++程序中的分段错误

Segmentation fault in C++ program using getline and string function

本文关键字:分段 错误 程序 C++ getline 字符串 函数 使用      更新时间:2023-10-16

我用C++写了一个示例程序,它崩溃了。我不知道为什么这会崩溃。任何帮助将不胜感激。

下面是示例程序:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

string foo(string b)
{
cout << b << endl;
}
int main(int argc, char* argv[])
{
string fileName = argv[1];
ifstream ifile(fileName.c_str(), ios::in);
string line;
while(getline(ifile , line))
cout << line << endl;
ifile.close();
foo("q");
return 0;
}

我将 1.txt 作为包含以下内容的参数传递:

a
b
c

我得到的输出是:

a
b
c
q
Segmentation fault

您将foo()声明为返回一个string对象,但foo()中没有return语句,因此返回值是不确定的,并且当编译器尝试管理返回的string时,代码具有未定义的行为

如果您不打算return任何内容,则需要将返回值声明为void

void foo(string b)
void foo(string b)
{
cout << b << endl;
return;
}