Question

So I trying to do an implementation of the List class but when trying to do the erase function I keep getting a pointer being freed was not allocated error.

Here is the code of my function erase():

template <class T> void List<T>::erase(ListIterator<T> & start, ListIterator<T> & stop)
{
    while (start<= stop) {
    ListIterator<T> * temp = &start;
    ++temp;
    delete start.currentLink;
    start.currentLink = temp->currentLink;
    }
}

Now I have already tested my link and listiterator class and they work I have done everything else like insert() and push_back(). I have not been able to find out where I the memory allocation goes wrong. is any ideas that might point me in the right direction.

Was it helpful?

Solution

According to your implementation you will be freeing same memory space in third iteration of while loop (i,e if you are freeing more than 2 element then you will probably get an error).

template <class T> void List<T>::erase(ListIterator<T> & start, ListIterator<T> & stop)
{
          while (start<= stop) {
              ListIterator<T> * temp = &start;
Line:1        ++temp;
Line:2        delete start.currentLink;
Line:3        start.currentLink = temp->currentLink;
    }
}

Consider ListClass = {A, B, C} with A.link = 100, B.link = 101 and C.link = 102

1st Iteration:

Line1: temp points to B

Line2: you free 100

Line3: you assign A.link = temp.link (i,e B.link) = 101

2nd Iteration:

Line1: temp still points to B

Line2: you free 101

Line3: you assign A.link = temp.link (i,e B.link) = 101 which is already freed

3rd Iteration

Line1: temp still points to same darn B

Line2: you free 101 which is already freed <--- probably gdb complains here

Easy Fix:

template <class T> void List<T>::erase(ListIterator<T> & start, ListIterator<T> & stop)
{
    ListIterator<T> * temp = &start;
    while (start<= stop) {
        ++temp;
        delete start.currentLink;
        start.currentLink = temp->currentLink;
    }
}

Better Fix:

template <class T> void List<T>::erase(ListIterator<T> & start, ListIterator<T> & stop)
{
    ListIterator<T> * temp = &start;
    while (start<= stop) {
        delete start.currentLink;
        start++;
    }
    temp->currentLink = start.currentLink;
}

Although I am confused regarding the erase function as last 2 element will have same currentLink (as far as I can guess from your implementation).

Hope this helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top