Search code examples
c++data-structureslinked-listcircular-list

Memory Error with Circularly Linked List: pointer being freed was not allocated


The program runs and the test does succeed, but between the list and the result of the test I get this: assignment_2.2(10729,0x7fff78db0300) malloc: * error for object 0x7fb132d00000: pointer being freed was not allocated * set a breakpoint in malloc_error_break to debug Any idea how I can fix this?

main.cpp

#include "OLinkedList.h"

using namespace std;

int main(int argc, char** argv) {
    OLinkedList CircleList;
    CircleList.fillList(0);
    CircleList.prntList();
    CircleList.OTest();
    return 0;
}

OLinkedList.h

#ifndef OLINKEDLIST_H
#define OLINKEDLIST_H

#include <iostream>
#include <iomanip>
using namespace std;

class OLinkedList{
private:    struct Link{
                int data;
                Link *next;
            };
            Link *head;
            Link *tail;
public:     OLinkedList(){head = nullptr; tail = nullptr;};
           ~OLinkedList();
       void fillList(int);
       void prntList();
       void OTest();

};

//Destructor for Class used to delete memory of list
OLinkedList::~OLinkedList(){
    Link *linkPtr = head;
    Link *nextPtr;

    //traverses to the end of the list to delete memory
    do
    {
        nextPtr = linkPtr->next;
        delete linkPtr;
        linkPtr = nextPtr;
    }while(linkPtr!= nullptr);
}

//
void OLinkedList::fillList(int size){    
    Link *front = new Link; //create first link
    head = front; //set first link = to traversal
    head->data = size++;         //Fill the front with data
    head->next = nullptr;     //Point the front to no where

    Link *temp = head;      
    do{
        Link *end = new Link;   //Create a new link
        end->data = size++;     //Fill with data
        end->next = nullptr;       //Point to no where
        temp->next=end;//Previous link will point to the end
        temp=end;  //Now this has become previous link  
        tail = end;
        tail->next = head;
    }while(size < 10);          //Repeat until filled

}

 void OLinkedList::prntList(){
    Link *linkPtr;

    linkPtr = head;
    int i = 0;
    do{
        cout<<"  "<<setprecision(3)<<linkPtr->data;
        linkPtr = linkPtr->next;
        i++;
    }while(i < 10);
}

//Used to prove list is circular
void OLinkedList::OTest(){
    Link *linkPtr = tail->next;
    cout<<"\nAfter "<<tail->data<<" is "<<linkPtr->data;
}
#endif /* OLINKEDLIST_H */

Solution

  • When you set tail->next to head, you are creating a circular linked list as intended. Your do while loop should check for linkPtr != head, rather than nullptr, since you are doing a double free on head. This is because deleting the pointer doesn't nullify any variable previously pointing to it, so your loop will eventually return to head.

    In fact, if not for the double free, your code would go into an infinite loop.