Eric
Eric

Reputation: 2705

Using a field in initialization list in constructor body

In the code below, I have a constructor that initializes requests vector in the initialization list using split_string function, which is a working function. I am using the vector in the constructor body, but it throws a segmentation fault if I try to construct a request class with command lines.

Why is this giving me an error? What is wrong?

class request {
    vector<char*> requests;

    public:

    explicit request(char line[]): requests(split_string(line)) {
        cout << "THIS LINE DOES NOT PRINT" << requests[1] << endl;
    }

This is the split_string code:

vector<char*> split_string(char line[]) {
    vector<char*> vec_str;
    char* token;
    token = strtok(line, " ");

    while (token != NULL) {
        vec_str.push_back(token);
        token = strtok(NULL, " ");
    }
    for(int i = 0; i < vec_str.size(); ++i) {
        std::cout << vec_str.at(i) << std::endl;
    }
}

Upvotes: 0

Views: 58

Answers (1)

timrau
timrau

Reputation: 23058

There is no return statement in split_string(). Thus, request::requests wasn't initialized by the correct vector<char*>.

Upvotes: 2

Related Questions