在C++中使用向量的分割错误

Segmentation fault using vectors in C++?

本文关键字:分割 错误 向量 C++      更新时间:2023-10-16

>我正在寻找我已编程到代码中的分割错误。当我的函数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)

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

一个错误是你没有从这个函数返回一个值:

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.