在单个链接列表示例中,显示是内存泄漏

问题描述 投票:0回答:1
Here is my code.

#include <bits/stdc++.h> 
using namespace std; 

class Node { 
public: 
    int data; 
    Node* next; 
}; 

void printList(Node* n) 
{ 
    while (n != NULL) { 
        cout << n->data << " "; 
        n = n->next; 
    } 
} 

void delete_list(Node *n)
{
    Node *tmp = NULL;
    tmp = new Node();
    while (n != NULL){
        tmp=n->next;
        delete (Node *)n;
        n=tmp;
    }
    delete (Node *)tmp;
}


int main() 
{ 
    Node* head = NULL; 
    Node* second = NULL; 
    Node* third = NULL; 

    head = new Node(); 
    second = new Node(); 
    third = new Node(); 

    head->data = 1; 
    head->next = second;

    second->data = 2;
    second->next = third; 

    third->data = 3;
    third->next = NULL; 

    printList(head); 

    // Delete the entire list
    delete_list(head);

    return 0; 
} 
  • HEAP摘要:enter code here退出时使用:1块中的16个字节堆总使用量:6个分配,5个释放,73,792字节分配1块中的16个字节肯定在1的丢失记录中丢失在0x4C3017F:运算符new(unsigned long)(在/usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so中)通过0x10895E:delete_list(Node *)(demo.cpp:24)通过0x108A87:主(demo.cpp:58)泄漏摘要:绝对丢失:1个块中的16个字节间接丢失:0字节(0块)可能丢失:0字节(0块)仍可访问:0字节(0块)已抑制:0字节,0块有关检测到和抑制的错误的计数,请重新运行:-v错误摘要:来自1个上下文的1个错误(禁止显示:0至0)
c++ valgrind
1个回答
1
投票
void delete_list(Node *n)
{
    Node *tmp = NULL;

    // this is your memory leak:
    // you just created a new node ...
    tmp = new Node();

    while (n != NULL)
    {
        // ... and very first thing you do is assigning another node to the only
        // pointer holding the node created just before
        tmp = n->next;

        delete (Node *)n;
        n = tmp;
    }

    // apart from cast being obsolete (tmp HAS appropriate type!)
    // tmp is already nullptr and you don't delete anything at all
    delete (Node *)tmp;
}

此示例很好地说明了为什么最好将变量保持在尽可能局部的位置:

while (n != NULL)
{
    Node* tmp = n->next;
    delete (Node *)n;
    n = tmp;
}

您根本无法在不需要时分配任何东西(甚至创建不相关的对象)或试图删除不再存在的东西...


0
投票

是的,我做了同样的事情。谢谢你们。

void delete_list(Node *n)
{
        Node *tmp = NULL;
//      tmp = new Node();
        while (n != NULL){
        tmp=n->next;
        delete (Node *)n;
        n=tmp;
    }
//    delete (Node *)tmp;
}

现在没有内存泄漏。 :)Memcheck,内存错误检测器版权所有(C)2002-2017,以及Julian Seward等人的GNU GPL。使用Valgrind-3.13.0和LibVEX;使用-h重新运行以获取版权信息命令:./ a.out1 2 3文件描述符:3在出口打开。打开文件描述符2:/ dev / pts / 3打开文件描述符1:/ dev / pts / 3打开文件描述符0:/ dev / pts / 3堆摘要:在出口使用:0字节,0块堆总使用量:5个分配,5个释放,73,776字节分配所有堆块都已释放-不可能泄漏有关检测到和抑制的错误的计数,请重新运行:-v错误摘要:0个上下文中的0个错误(禁止显示:0个中的0个)

© www.soinside.com 2019 - 2024. All rights reserved.