2017-10-08 83 views
-2

我想清除我的代码下面的内存泄漏。我把它清理干净并将其简化为最简单的形式。我不断从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; 
} 
+6

你不应该写,需要使用手动'delete'开始与代码。 –

+1

Std :: vector会给你没有新/删除麻烦的需要,所以没有内存泄漏。 – stefaanv

+0

这对数组的整数,双精度等效果都很好。但是在对象数组的情况下,在使用delete []时,某些编译器不支持调用数组中对象的每个析构函数。因此,不得不调用每个析构函数来释放内存。 –

回答

4

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

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

既然你有两个呼叫new,你需要两个相应delete/delete[]电话。

4

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

简单

std::vector<Player> myPlayer; 

就足够了。

避免做动态内存管理手卷,这是容易出错和悲伤和麻烦一致的来源。


如果可能的话,我想主要申报阵列。

这里是一个修改后的代码:

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