Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
143 views
in Technique[技术] by (71.8m points)

C++ trouble with deallocating memory taken by vector elements

So the problem is that when i try to push non-dynamic obj to playerList or when I try to delete n I get segfault (core dump). I assume that the problem is caused when Helper class is being destroyed so the vector also is being destroyed so it tries to destroy object in itself which does not exist anymore. However when i use playerList.clear() the problem still exist. I think i could just destroy objects in playerList() with ~Helper(). But I would like to know why i cannot use non-dynamic objects and just clear them out of playerList at the end of Run().

class Helper{
public:

    void Run();


private:
    std::vector<Player>playerList;
    ...
};

that's how Run() looks like:

using namespace std;

void Helper::Run(){
    Player *n = new Player();
    playerList.push_back(*n); //Yup. There is a memleak
}

also Player.h:

class Player{
public:

    ...
    ~Player();

private:
    ...
    IClass* typeOfClass = new Warrior();
};

and ~Player:

Player::~Player(){
    delete typeOfClass;
}

and Warrior (has no effect on the problem)

class Warrior {
public:

    int GetMeleeAttack();
    int GetRangedAttack();
    int GetMagicAttack();
    int AgilityAction();
    int StrengthAction();
    int IntelligenceAction();
    void WhoAmI();

private:

};

Warrior's methods just returns some integers.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
std::vector<Player>playerList;

should be

std::vector<Player*>playerList;

if you want to allocate them dynamically. The other method would be to emplace each element and not use new.

When using new you are allocating on the heap but you are creating a new element in the vector by passing the value from the one allocated on heap. And you have a dangling pointer ( memory leak )

Remember to deallocate all the elements at the destruction of the vector if you are using a vector of pointers.

Another method would be:

 std::vector<std::unique_ptr<Player> >playerList;

That will take care of the allocation issue.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...