DoublyLList C ++ // Insert value in position index (with iterator)

0

My function to insert is correct, but I'm having memory leak because when I debugged, temp->prev->prev was pointing to nullptr instead of pointing to the rest of the list when it has 3+ elements.

Note: The 'address' of the leak is pointing to Node* temp = new Node...

void DLList<Type>::insert(DLLIter<Type>& index, const Type & v)
{
    if (index.m_curr == nullptr)
        return;

    Node* temp = new Node(v, index.m_curr->m_prev); // valor, m_prev
    temp->m_next = index.m_curr;

    if (index.m_curr == m_head)
    {
        temp->m_next = m_head;
        m_head = temp;
        index.m_curr = temp;
    }
    else
    {
        index.m_curr->m_prev->m_next = temp;
        index.m_curr = temp;
    }

    ++m_size;
}

Is the function completely correct and the leak is coming from somewhere else, or is the problem there?

    
asked by anonymous 08.03.2016 / 00:52

1 answer

0

There were a few missing connections between the list and the temp.

void DLList<Type>::insert(DLLIter<Type>& index, const Type & v)
{
if (index.m_curr == nullptr)
    return;

Node* temp = new Node(v, index.m_curr->m_prev);
temp->m_next = index.m_curr;

if (index.m_curr == m_head)
{
    temp->m_next = m_head;
    m_head = temp;
    index.m_curr = temp;
}
else
{
    index.m_curr->m_prev->m_next = temp;
    temp->m_prev = index.m_curr->m_prev;
    temp->m_next = index.m_curr;
    index.m_curr->m_prev = temp;
    index.m_curr = temp;
}

++m_size;
}
    
08.03.2016 / 03:27