为什么我在这里收到内存泄漏?

时间:2016-07-14 22:36:40

标签: c++ memory-leaks linked-list queue

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;
        }
    }
}

在main函数中,我只是实例化一个空的Queue,添加一个项目,然后对一个项目进行排队,我得到内存泄漏,我觉得它与我的dequeue方法或我的析构函数有关。 ..

虽然,我是C ++的新手,所以我不完全确定。

有谁愿意帮助我吗?

编辑:

我输入了user4581301建议的更改,并且在修改时修复了我的内存泄漏问题

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

但是,如果我删除q.dequeue()并将其留给析构函数,那么我会收到内存泄漏。

2 个答案:

答案 0 :(得分:1)

Queue::dequeue

Node* node = new Node();

分配一个新节点,其地址被

迅速覆盖和泄露
node = front;

替换两行
Node* node = front; 

立即指向node front就足够了。

正如Miles Budnek指出的那样,同样的错误发生在Queue::print。除非您绝对必须,否则不要new,并且所有new必须在某处具有相应的delete

答案 1 :(得分: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()之外宣布,以便它不会超出范围。