为什么推送到向量指针时会出现分段错误

Why does segmentation fault occur when pushing to pointer of vector

我正在尝试学习c++,想编写一个简单的程序来探索向量和指针的使用。当我尝试 运行 一个使用此函数的简单程序时,出现了分段错误。当我改变

std::vector<string> *data;

std::vector<string> data;

并将“->push_back()”更改为“.push_back()”,运行没问题。

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;

}

您的代码生成了一个段错误,因为您没有为您的指针分配内存。

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;

}

请注意,您需要在使用完后 delete 它,但实际上动态分配 std::vector 没有意义,它将分配其中所需的所有内容,您赢了不必冒内存泄漏的风险,因为您不必到处追逐 delete