使用删除/删除[]但仍有内存泄漏

时间:2017-10-08 19:42:36

标签: c++ memory-leaks

我想从下面的代码中清除内存泄漏。我将其清理干净并将其缩小为最简单的形式。我一直在从valgrind那里得到内存泄漏。我想使用一个对象数组来编译名称列表,而不是清理内存,以便最后没有泄漏。如果可能的话,我想在main中声明数组。

//in Player.h

#include <iostream>
#include <string>
#include <string>
#include <cstring>

class Player
{
    private:
        std::string first, last;

    public:

        Player();

        ~Player(); //I tried my code with and without this destructor

        Player(std::string first_name, std::string last_name);
    };

//in player.cpp

#include "Player.h"
#include <iostream>
#include <string>
#include <cstring>

Player::Player(std::string first_name, std::string last_name)
{
    this->first=first_name;
    this->last=last_name;
}

Player::~Player() 

{  //I tried both commands below separately and I still have memory leaks

    //delete [] Player; 
    //delete [] myPlayer;
}

// in Driver.cpp


#include "Player.h"
#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>

int main() 
{
    std::string temp_First, temp_Last;
    Player *myPlayer[2];

    temp_First="John";
    temp_Last="Smith";

    myPlayer[0] = new Player(temp_First, temp_Last);

    temp_First="Poca";
    temp_Last="Hontas";

    myPlayer[1] = new Player(temp_First, temp_Last);

    delete [] myPlayer; 

    return 0;
}

2 个答案:

答案 0 :(得分:4)

您需要单独释放myPlayer的每个元素:

delete myPlayer[0];
delete myPlayer[1];

由于您有两次拨打new,因此您需要进行两次相应的delete/delete[]来电。

答案 1 :(得分:4)

为什么需要在代码中使用new / delete

一个简单的

 std::vector<Player> myPlayer;

就足够了。

避免动态内存管理手动,它容易出错,并且是一直存在的悲伤和麻烦。

  

如果可能的话,我想在main中声明数组。

以下是修改后的代码:

int main() 
{
    std::vector<Player> myPlayer {
        { "John", "Smith" } ,
        { "Poca", "Hontas"}
    };
    return 0;
}