2017-10-08 81 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; 
}