首页 > 解决方案 > 在 C++ 中使用向量的分段错误?

问题描述

我正在寻找已编程到我的代码中的分段错误。parseRecord(string)当我的函数生成一个向量并且我想打印出其中一个元素时,它基本上会出现。我已将其范围缩小到这一点,但找不到错误。向量是 Record 对象,它们是通过读取文件创建的,该文件每行有一行数据。

每当我创建类的对象(不创建向量)时,我都可以很好地打印元素。它仅在我使用创建向量的 parseRecord(string) 函数时出现。

我还尝试在函数本身中以相同的结果打印它。所以我认为这不是范围问题。

#include <iostream>
#include <fstream>
#include <iomanip>
#include <vector>

#include "record.hpp"

ifstream parsefile(string filename);
std::vector<Record> parseRecord(string line);

int main(int argc, char const *argv[])
{
    std::vector<Record> dataSet = parseRecord("data.dat");

    Record record("D11101001", "Max", "Muestermann",
                  10239, "fictionalmarkt.com", "23.12.19", "11:11:00");

    cout << record;

    for(std::vector<Record>::const_iterator i = dataSet.begin(); i != dataSet.end(); ++i){
        cout << *i << endl;
    }
    return 0;
}

//METHOD-IMPLEMENTATION
//parse-file definition - Test if file is accessible
ifstream parsefile(string filename)
{
    ifstream inFile(filename);
    if (!inFile)
    {
        cerr << "File could not be opened" << endl;
        exit(-1);
    }
    cout << "Input-file is readable!" << endl;
    return inFile;
}

//parse-record definition - read file, add to vector<Record> and return vector
std::vector<Record> parseRecord(string filename)
{
    vector<Record> dataSet;

    ifstream inFile = parsefile(filename);
    string line;

    while (getline(inFile, line))
    {
        stringstream linestream(line);
        string accountNb;
        string firstName;
        string lastName;
        string amountStr; //format 100 = 1.00€
        string merchant;
        string date;
        string time;
        long double amount;

        getline(linestream, accountNb, '|');
        getline(linestream, firstName, '|');
        getline(linestream, lastName, '|');
        getline(linestream, amountStr, '|');
        getline(linestream, merchant, '|');
        getline(linestream, date, '|');
        getline(linestream, time, '\n');

        try
        {
            amount = stold(amountStr);
        }
        catch (const std::exception &e)
        {
            std::cerr << e.what() << '\n'
                      << "Conversion error";
        }

        amount *= 100.0; //to correct the decimal format

        Record recordEntry(accountNb, firstName, lastName, amount, merchant, date, time);

        //cout << recordEntry << endl;

        dataSet.push_back(recordEntry);
    }

    return dataSet;
}

记录.hpp

class Record
{
private:
    string accountNb;
    string firstName;
    string lastName;
    long double amount; //format 100 = 1.00€
    string merchant;
    string date;
    string time;
public:
    Record(string, string, string, long double, string, string, string);
    ~Record();
    friend ostream& operator<<(ostream&, const Record&);
};

记录.cpp

#include "record.hpp"
#include <ostream>

Record::Record(string accountNb, string firstName, string lastName,
               long double amount, string merchant, string date, string time)
{
    this->accountNb = accountNb;
    this->firstName = firstName;
    this->lastName = lastName;
    this->amount = amount;
    this->merchant = merchant;
    this->date = date;
    this->time = time;
}

Record::~Record()
{
}

ostream &operator<<(ostream &os, const Record &rec)
{
    os << right;
    os << setw(15) << "Account Nb:" << setw(50) << rec.getAccountNb() << endl;
    os << setw(15) << "First Name:" << setw(50) << rec.getFirstName() << endl;
    os << setw(15) << "Last Name:" << setw(50) << rec.getLastName() << endl;
    try
    {
        os << showbase;
        os << setw(15) << "Amount:" << setw(50);
        os.imbue(std::locale("de_DE.UTF-8"));
        os << put_money(rec.getAmount(), true) << endl;
    }
    catch (const std::exception &e)
    {
        std::cerr << e.what() << "locale not supported system";
    }
    os << setw(15) << "Merchant:" << setw(50) << rec.getMerchant() << endl;
    os << setw(15) << "Date:" << setw(50) << rec.getDate() << endl;
    os << setw(15) << "Time:" << setw(50) << rec.getTime() << endl;
}

结果控制台打印:

Account Nb:                                         D11101001
First Name:                                               Max
 Last Name:                                       Muestermann
    Amount:                                       102,39 EUR
First Name:                                             Jonny
 Last Name:                                               Doe
    Amount:                                        80,38 EUR
  Merchant:                                          markt.de
      Date:                                          25.12.19
      Time:                                         11:11:19
Segmentation fault (core dumped)

所以它在第一行之后退出。

标签: c++vectorsegmentation-fault

解决方案


一个错误是您没有从此函数返回值:

ostream &operator<<(ostream &os, const Record &rec)

不从声明为返回值的函数返回值是未定义的行为。

ostream &operator<<(ostream &os, const Record &rec)
{
    //...
    return os; // <-- you are missing this line
}

以上是明显的错误,但另一个潜在错误是在您对有效double. double您捕获了一个异常,但是当它实际上未初始化时,您的代码就好像它是有效的一样继续运行。

double amount;  // <--uninitialized.
//..
try
{
   amount = stold(amountStr);
}
catch (const std::exception &e)
{
   std::cerr << e.what() << '\n' << "Conversion error";
}

amount *= 100.0; // <-- behavior undefined if exception above this line was thrown.

推荐阅读