2016-07-14 46 views
-1

Main.cpp的为什么我在这里得到内存泄漏?

#include<iostream> 
#include "Queue.h" 

using namespace std; 
char* PotionTypeString(PotionType type) 
{ 
    char* s = "UNKNOWN"; 

    switch (type) { 
    case SPEED: 
     s = "Speed"; 
     break; 
    case STRENGTH: 
     s = "Strength"; 
     break; 
    case HEALTH: 
     s = "Health"; 
     break; 
    case WISDOM: 
     s = "Wisdom"; 
     break; 
    } 
    return(s); 
} 

int main() 
{ 
    Queue q; 
    q.enqueue(WISDOM); 
    q.dequeue(); 
    #ifdef _WIN32 
    if (_CrtDumpMemoryLeaks()) { 
     cout << "Memory leaks!" << endl; 
    } else { 
     cout << "No leaks" << endl; 
    } 
    #endif 
    return 0; 
} 

Queue.cpp

#include "Queue.h" 
#include <string.h> 
#include <iostream> 

using namespace std; 

Queue::Queue() { 
    front = NULL; 
    rear = NULL; 
    size = 0; 
} 

Queue::~Queue() { 
    Node* cur = front; 

    while (cur != NULL) { 
     Node* temp = cur->next; 
     delete cur; 
     cur = temp; 
    } 
} 

void Queue::enqueue(PotionType type) { 
    Node* node = new Node(); 
    node->type = type; 

    if (front == NULL) { 
     front = node; 
    } 
    else { 
     rear->next = node; 
    } 
    rear = node; 
    size = size + 1; 
} 

PotionType Queue::dequeue() { 
    PotionType toRet; 
    if (front != NULL) { 
     Node* node = new Node(); 

     node = front; 
     front = front->next; 

     toRet = node->type; 
     delete(node); 
     size = size - 1; 
    } 
    return toRet; 
} 

void Queue::print() { 
    if (front == NULL) { 
     cout << "Empty list" << endl; 
    } 
    else { 
     Node * toPrint = new Node(); 
     toPrint = front; 

     while (toPrint != NULL) { 
      cout << PotionTypeString(toPrint->type) << endl; 
      toPrint = toPrint->next; 
     } 
    } 
} 

在主函数我只实例化一个空队列,添加单个项目,然后去排队的单个项目,我发现内存泄漏,我觉得它与我的出队方法或我的析构函数有关...

虽然,我对C++有些新鲜,所以我不是完全确定。

有人愿意帮助我吗?

编辑:

我把由user4581301建议的修改,并固定时只是要

Queue q; 
q.enqueue(WISDOM); 
q.dequeue(); 

但是,如果我去掉q.dequeue(),离开它我的内存泄漏问题直到析构函数然后,我收到一个内存泄漏。

回答

1

Queue::dequeue

Node* node = new Node(); 

分配一个新的节点谁的地址是及时覆盖,并通过

node = front; 

front

Node* node = front; 

更换两行立即指向node泄露应就足够了。

至于布里克指出,同样的错误在Queue::print。除非你绝对必要,否则不要new,并且所有new都必须有相应的delete

+0

'Queue :: print'发生同样的事情。 –

+0

@ user4581301我用更多的信息编辑了OP。 –

+0

@DylanHolmes'Queue q;'分配一个静态'Queue',在'main'函数退出之前不会被销毁。这是在你打电话给泄漏检查器之后。如果你减少了'q'的范围,然后调用泄漏检查器,那么泄漏将会消失,或者你在析构函数中有一个错误。试试这个:'{Queue q; q.enqueue(WISDOM);}在结束大括号和检漏仪之前销毁''q'。我推荐阅读[三条法则是什么?](http://stackoverflow.com/questions/4172722/what-is-the-rule-of-ree),因为它可能会回答下一个问题,至今还没有得到解决,题。 – user4581301

0

使用指针后,将其删除,然后将其设置为NULL。例如:

char* PotionTypeString(PotionType type) 
{ 
    char* s = "UNKNOWN"; 

    switch (type) { 
    } 
return(s); 
} 

int main() 
{ 
    Queue q; 
    q.enqueue(WISDOM); 
    q.dequeue(); 
    delete s; 
    s = NULL; 
    #ifdef _WIN32 
    #endif 
    return 0; 
} 

当然,对于这个工作,s将外PotionTypeString()中声明,这样就不会超出范围。