微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

== 20556 == 1个块中的16个字节肯定在丢失记录1 of 1中丢失

如何解决== 20556 == 1个块中的16个字节肯定在丢失记录1 of 1中丢失

我为我创建的链表类编写了很多函数,但是由于某种原因,我的内存泄漏源于append-> insert_back-> insert函数。随附的是每个代码

追加:

void LinkedList<T>::append(const LinkedList<T> &l2)
{
    if (l2.isEmpty())
    {
        return;
    }

    //Set current position to l2 head
    LLNode<T> *curr = l2.m_head;
    //For as long as curr->next is not NULL insert to the back of this list the l2 list values
    for(curr; curr->m_next != NULL; curr = curr->m_next){
        insert_back(curr->m_data);
    }
}

重新插入:

void LinkedList<T>::insert_back(const T &x)
{
    if (isEmpty())
    {
        //If the list is empty then use alternative method to store data in back
        LLNode<T> *tmp = m_head;
        while (tmp->m_next != NULL)
        {
            tmp = tmp->m_next;
        }
        insert(x,tmp);
    }
    else
    {
        insert(x,getAtPtr(m_size));
    }
}

插入:

void LinkedList<T>::insert(const T &x,LLNode<T> *pos)
{
    //Create tmp node to store position,set current position data to be passed in x,sets next position to be tmp
    //variable.
    LLNode<T> *tmp = new LLNode<T>;
    *tmp = *pos;
    pos->m_data = x;
    pos->m_next = tmp;
    m_size++;
}

这是valgrind发出的确切的内存链接错误消息:

void LinkedList<T>::insert(const T &x,LLNode<T> *pos)
{
==21462== 16 bytes in 1 blocks are definitely lost in loss record 1 of 1
==21462==    at 0x4C3017F: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==21462==    by 0x10C4A0: LinkedList<int>::insert(int const&,LLNode<int>*) (in /home/laner107/CS1575/Homework/Homework 2/Homework2/tester.ex)
==21462==    by 0x10BACB: LinkedList<int>::insert_back(int const&) (in /home/laner107/CS1575/Homework/Homework 2/Homework2/tester.ex)
==21462==    by 0x10C1E4: LinkedList<int>::append(LinkedList<int> const&) (in /home/laner107/CS1575/Homework/Homework 2/Homework2/tester.ex)
==21462==    by 0x10AD81: test05() (in /home/laner107/CS1575/Homework/Homework 2/Homework2/tester.ex)
==21462==    by 0x10B46E: main (in /home/laner107/CS1575/Homework/Homework 2/Homework2/tester.ex)

此内存链接发生在哪里?预先谢谢你!

解决方法

您正在分配LLNode<T>并将其分配给tmp。然后将tmp分配给pos。新分配的LLNode<T>发生了什么?它被泄漏了。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。