2013-04-10 43 views
0

我的Queue类有内存泄漏。我使用valgrind来定位内存泄漏,并且这两次都发生在同一行上。该行在代码中标记。在队列中泄漏内存

template <typename T> 
void Queue<T>::enqueue(const T& x) 
{ 

    if(isEmpty()) 
    { 
     Queue<T>* temp = new Queue<T>();//THIS IS THE LEAKED MEMORY 
     m_data = x; 
     m_next = temp; 
     temp->m_next = NULL; 
     return; 

    } 


    Queue<T>* temp = this; 

    while(temp->m_next != NULL) 
    { 
     temp = temp->m_next; 
    } 
    Queue<T>* node = new Queue<T>(); 
    temp->m_data = x; 
    node->m_next = temp->m_next; 
    temp->m_next = node; 
    return; 
} 

功能isEmpty()如下:

template <typename T> 
bool Queue<T>::isEmpty() const 
{ 
    return (m_next==NULL); 
} 

这个任何想法将是巨大的。

+0

您正在分配一个新的队列但从来没有释放它。至少不在你显示的代码中。 – 2013-04-10 21:40:03

+0

这不是我的那个downvoted:但你不需要在void方法结束时返回这个返回 – 4pie0 2013-04-10 21:40:13

+0

每个New都应该有一个Delete来匹配它!你能向我们展示匹配的删除吗? – 2013-04-10 21:42:59

回答

0
Queue<T>* temp = new Queue<T>();//THIS IS THE LEAKED MEMORY 

这是因为你有自由的地方记忆,通过

delete temp;

,也许你不这样做。不在你已经显示的代码中。所以在适当的时候简单地删除它

0

我能够解决这个错误。它在代码中的其他地方。发布这个问题后我几乎立即发现它。谢谢您的帮助。