简体   繁体   English

赛格。 在std :: vector上推送指针时出错

[英]Seg. Fault When Pushing a Pointer on a std::vector

I have profiled the following code with Valgrind and got the following: 我用Valgrind描述了以下代码并得到了以下内容:

Use of uninitialised value of size 8
invalid read of size 8

when executing this line: 执行此行时:

compuMethod->keywordlist->push_back(keyword);

However, I have clearly initialized keyword ... 但是,我已经明确初始化了keyword ......

#include <iostream>
#include <vector>
#include <map>
#include <string>
using namespace std;

class Keyword;
class CompuMethod;

typedef std::vector<Keyword*> KeywordList;
std::map<std::string, CompuMethod*> AllCompuMethods;

class Keyword
{
    private:
        std::string _name;

    public:
        Keyword(std::string name) : _name(name) {}
        virtual ~Keyword() {}
        std::string GetName() { return(_name); }
};

class CompuMethod
{
    public:
        CompuMethod(){}
        ~CompuMethod(){}
        KeywordList* keywordlist;

};

int main()
{
    CompuMethod* compuMethod = new CompuMethod();
    Keyword* keyword = new Keyword("terminal");
    compuMethod->keywordlist->push_back(keyword);

    //Call delete for each new
    return 0;
}

I am obviously overlooking something. 我显然忽略了一些东西。 What am I doing on this line: 我在这方面做了什么:

Keyword* keyword = new Keyword("terminal");

that is NOT initializing keyword ? 那不是初始化keyword

keyword is initialised correctly. keyword已正确初始化。 The problem is that you didn't allocate compuMethod->keywordlist 问题是你没有分配compuMethod->keywordlist

You should either make keywordlist a KeywordList rather than a pointer or allocate it in CompuMethod() (deleting it in the destructor) 您应该做keywordlist一个KeywordList ,而不是一个指针或分配它CompuMethod()在析构函数删除它)

keywordlist is a pointer to std::vector<Keyword*> keywordlist是指向std::vector<Keyword*>的指针

You can't simply push items into it. 你不能简单地将物品推入其中。

Use following to allocate memory for the pointer to vector in the Constructor 使用以下命令为构造函数中的向量指针分配内存

CompuMethod(){keywordlist = new KeywordList();}

And accordingly update the Destructor 并相应地更新析构函数

~CompuMethod(){ delete keywordlist; }

Edit : 编辑

greyfade comment - greyfade评论 -

" But don't forget the copy/move ctor and operator= to properly handle the pointer. Otherwise, you'll end up with double-frees " 但是不要忘记复制/移动ctor和operator =正确处理指针。否则,你最终将获得双重释放

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM