使用valgrind时,会出现2次内存泄漏,我无法理解它来自哪里..
这是valgrind给出的错误:
==22759== 192 bytes in 12 blocks are definitely lost in loss record 1 of 3
==22759== at 0x4C2E0EF: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==22759== by 0x402ABA: FigureCard::clone() (Card.cpp:139)
==22759== by 0x403464: Deck::operator=(Deck const&) (Deck.cpp:39)
==22759== by 0x40A8A4: Game::Game(char*) (Game.cpp:51)
==22759== by 0x40FACC: main (reviiyot.cpp:18)
==22759==
==22759== 5,280 bytes in 330 blocks are definitely lost in loss record 2 of 3
==22759== at 0x4C2E0EF: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==22759== by 0x4030CC: NumericCard::clone() (Card.cpp:228)
==22759== by 0x403464: Deck::operator=(Deck const&) (Deck.cpp:39)
==22759== by 0x40A8A4: Game::Game(char*) (Game.cpp:51)
==22759== by 0x40FACC: main (reviiyot.cpp:18)
卡片中的clone():
Card* NumericCard:: clone()
{
Card* c=new NumericCard(*this);
return c;
}
operator = in Deck:
Deck& Deck:: operator=(const Deck& other)
{
clean();
vector <Card*> *c=new vector<Card*>;
c->clear();
for(int i=0;i<((int)other.getCards()->size());i++)
{
Card* c1=other.getCards()->at(i)->clone();
c->push_back(c1);
}
this->cards=c;
return *this;
}
FigureCard ctor:
FigureCard :: FigureCard(const Shape &shape,const Figure &figure):Card(shape),figure(figure){}
Card ctor:
Card::Card(Shape Pshape):shape(Pshape){}
NumericCard ctor:
NumericCard :: NumericCard(const Shape &shape,const int &number):Card(shape),number(number){}
DealCards-当我将Card指针发送到玩家的Card指针的链接列表时:(这就是我使用Card指针的原因)
void Deck:: dealCards(vector<Player*> players){
for(int j=0;j<((int)players.size());j++){
for(int i=0;i<7;i++){
Card* c=this->fetchCard();
players.at(j)->addCard(*(c));
delete c;
}
players.at(j)->removeQuatro(); //check for reviiya
}
for(int i=0;i<((int)players.size());i++){
players.at(i)->setInitialState();
}
this->initiaState=this->toString();
}
fetchCard:
Card* Deck:: fetchCard(){//Returns the top card of the deck and remove it from the deck
if(cards!=NULL){
if(!(this->cards->empty())){
Card* temp=cards->front();
cards->erase(cards->begin());
return temp;
}
else{
return NULL;
}
}
else{
return NULL;
}
}
清除linkedList:
void linkedList::clear()
{
link* temp=first;
while (temp != nullptr) {
first=temp->getNext();
temp->removeLinkToTrash();
temp=first;
}
}
removeLinkToTrash:
void link :: removeLinkToTrash(){
if(this->getPrev()!=NULL) // if it's not first link
this->prev->next=this->next;
if(this->getNext()!=NULL) //if its not last card
this->next->prev=this->prev;
clear();
}
清除链接:
void link:: clear(){
delete this->data;
delete this;
}
Deck析构函数 - 如果最后,它仍然有卡片:
Deck::~Deck() {
clean();
}
void Deck:: clean(){
if(cards!=NULL){
for(int i=0;i<((int)cards->size());i++){
delete cards->at(i);
}
}
delete cards;
}
感谢
答案 0 :(得分:1)
我建议您使用unique_ptr。这是一个内存泄漏安全的C ++类,它包含了经典的C指针。你使用make_unique(构造函数参数)创建它,你不必费心使用new / delete,你可以使用get()方法从它获得一个经典的C指针,如果确实需要你可以将它包含的资源的所有权移动到anotehr unique_ptr with move()。