Doublyllist C++ // Insert value at index position (with iterator)

Asked

Viewed 74 times

0

My insert function is correct, but I’m having memory Leak because when I debug, 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 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;
}

The function is totally correct and Leak is coming from somewhere else, or the problem is right there?

1 answer

0

It was missing some 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;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.