Why does segmentation fault occur when pushing to pointer of vector

I am trying to learn c++ and wanted to write a simple program to explore the use of vectors and pointer. When I try to run a simple program that uses this function a segmentation fault occur. When I change

std::vector<string> *data;

to

std::vector<string> data;

and change the ‘->push_back()’ to a ‘.push_back()’ it runs fine.

int simple_tokenizer(string s)
{
    std::stringstream ss(s);
    std::vector<string> *data;
    string word;
    //char delimiter = ',';
    while(getline(ss,word, ',')) {
        //cout << "charsplit" << word << endl;
        data->push_back(word);
    }
    return 0;//data;

}

Answer

Your code is generation a segmentation fault because you didn’t allocate memory for your pointer.

int simple_tokenizer(string s)
{
    std::stringstream ss(s);
    std::vector<string> *data = new std::vector<string>();
    string word;
    //char delimiter = ',';
    while(getline(ss,word, ',')) {
        //cout << "charsplit" << word << endl;
        data->push_back(word);
    }
    return 0;//data;

}

Mind you you need to delete it once you are done using it, but really there is no point in allocated an std::vector dynamically, it will allocating everything needed within it, and you won’t have to risk memory leaks because you won’t have to chase it around with delete everywhere.