2

The code is:

std::string fname;
std::cin >> fname;

When the code lies in main function, everything goes well. But when I put these two lines inside a member function, I get a segmentation fault atruntime.

Can anyone give me some hint on what is going on?

Minimal example:

#include <iostream>
#include <fstream>
#include <vector>
#include <string>
class TextQuery {
private:
    std::vector<std::string> *lines_of_text;
public:
    void retrieve_text();
};

void TextQuery::retrieve_text() {
    std::cout<<"Please input file name:\n";
    std::string fname;
    std::cin >> fname;
    std::ifstream fcontent(fname.c_str(), std::ios::in);
    std::string text_line;
    while(getline(fcontent, text_line, '\n')) {
        lines_of_text->push_back(text_line);
    }
}


int main() {
    TextQuery tq;
    tq.retrieve_text();
    return 0;
}

I am using g++ 4.2.1 on MacOS.

Lily Hao
  • 31
  • 6
  • 6
    Please provide a full [mcve], so we can reproduce the problem and see what you might be doing with pointers (the usual cause of segfaults). There's not enough context in your current question to even guess what the problem might be. – BoBTFish May 21 '18 at 06:37
  • 1
    @BoBTFish The minimal example is provided as above. – Lily Hao May 21 '18 at 06:52
  • 2
    `std::vector *lines_of_text` is unallocated pointer – SHR May 21 '18 at 06:52
  • A small point, you don't need to use `c_str()` to open a file stream these days. It used to be true, but since 2011 you can open a stream with a `std::string` as the filename. Other than that, the code style is a lot better than I see from many beginners here! May I ask where you are learning from? A book? A school/university/college teacher? – BoBTFish May 21 '18 at 07:00
  • You almost never need a pointer to a vector. – n. m. could be an AI May 21 '18 at 09:32
  • Excuse me for that I didn't read your last comment until today. This code is an example I learned from _C++ Premier_.@BoBTFish – Lily Hao Jun 28 '18 at 05:13

1 Answers1

5

You declare a member pointer but not allocate the object

std::vector<std::string> *lines_of_text;

But why are you using a pointer? you can declare it as a member object

std::vector<std::string> lines_of_text;
SHR
  • 7,940
  • 9
  • 38
  • 57