c ++ - 关于内存泄漏 - 新的

时间:2014-11-13 23:00:58

标签: c++ memory-leaks

我正在学习一些c ++并且有一个关于内存泄漏的简单问题。使用new创建的所有内容也应该被删除吗?

因此,例如,此代码应该有内存泄漏:

#include <iostream>

struct Node
{
  int data;
  Node* next;
};

bool insert(Node** head, int val)
{
    Node* temp = *head;

    if((*head)->data == val)
        return false;

    if(*head == nullptr || (*head)->data > val)
    {
        Node* new_node = new Node();

        new_node->next = *head;
        new_node->data = val;

        *head = new_node;

        return true;
    }

    while(temp->next != nullptr && temp->next->data <= val)
    {
        temp = temp->next;

        if(temp->data == val)
            return false;
    }

    //Sätt in ny nod
    Node* new_node = new Node{val, temp->next};
    temp->next = new_node;

    return true;
}

void print(Node** head)
{
    Node* temp = *head;

    while(temp != nullptr)
    {
        std::cout << temp->data << ' ';
        temp = temp->next;
    }
}

int main()
{
    Node* head = new Node{0, nullptr};
    Node* another = new Node{1, nullptr};
    head->next = another;

    for(unsigned i = 0; i != 10; ++i)
        if(insert(&head, i % 5))
            std::cout << "Inserted " << i % 5 << " into the list.\n";
        else
            std::cout << "Could not insert " << i % 5 << " into the list.\n";

    std::cout << "List is: ";
    print(&head);

    insert(&head, -1);
    insert(&head, 22);
    insert(&head, 13);
    insert(&head, 11);
    insert(&head, 19);

    std::cout << "\nList is: ";
    print(&head);

    return 0;
}

我正在尝试了解内存泄漏,所以我必须遍历结构并删除所有内容,或者仅仅删除“head”和“another”以防止此代码出现内存泄漏。< / p>

提前致谢

1 个答案:

答案 0 :(得分:0)

不,删除“head”和“another”是不够的。在此代码中,每个insert()调用都会分配一个新节点,因此如果您要添加正确的清理代码,则需要遍历链接列表并删除列表中的每个节点。由于节点只保存指向另一个节点的指针,因此它没有关于谁拥有该节点的信息,也不会自动删除它。

因此,您通常需要创建一个实际的“列表”结构来管理分配,然后销毁它的析构函数中的节点。

相关问题