c++ - 字符串分配的段错误

标签 c++ string segmentation-fault assign

我有一个文本文件,其中仅包含带有如下消息的行:

Hello there
howdy

现在我得到了这个读取这些行并返回包含它们的数组的函数。

string* printlines(string filename)
{
string line;
int sum = 2;
int i =0;
string *quotes;
ifstream infile(filename.c_str());

quotes= new string[2];

    if (infile.is_open())
    {

      while (infile.good())
      { 
        getline (infile,line);
        quotes[i] = line; // <--- here's the problem
        i++;
       }
    }
infile.close();
return quotes;
}

gdb 报告粗体行有问题,但我没有看到。

最佳答案

循环结构不正确,将导致超出数组末尾。即使文件中只有两行,在 getline() 之后也没有检查以确定是否成功。将读取前两行,但 eof 尚未设置,导致第三行 getline()调用,超出数组的末尾。

更改为:

while (getline(infile, line) && i < 2)
{
    quotes[i] = line;
    i++;
}

话虽如此,考虑使用 std::vector<std::string>而不是数组:

std::vector<std::string> quotes;
while (getline(infile, line))
{
    quotes.push_back(line);
}

std::vector将动态增长以存储所有读取行。无需更改代码即可将新行添加到文本文件。

关于c++ - 字符串分配的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10554404/

相关文章:

c++ - 在 OpenGL 中绘制扭曲平面的正确方法是什么?

c++ - Makefile 头目录错误

string - Powershell,计算文本文件中的字符串出现次数

C++ : Segmentation fault when call method of another class

c++ - 让我难过的基本指针算术

c++ - std::atomic_flag 初始化结果

javascript - 如何检查 Javascript 中 Unicode 字符串的相等性?

javascript - 如何将变量放入cookie中?

更改 argv 后的 C 段错误

c - c 中的段错误(核心转储)