-1

Here is the declaration of node.

template <typename E> class Link {
private:
    static Link<E>* freelist;
public:
    E element;
    Link* prev;
    Link* next;

    Link(const E& it, Link* prevp, Link* nextp) {
        element = it;
        prev = prevp;
        next = nextp;
    }
    Link(Link* prevp = NULL, Link* nextp = NULL) {
        prev = prevp;
        nextp = nextp;
    }

    void* operator new(size_t) {
        if(freelist == NULL)
            return ::new Link;
        Link<E>* temp = freelist;
        freelist = freelist->next;
        return temp;
    }

    void operator delete(void* ptr) {
        ((Link<E>*) ptr)->next = freelist;
        freelist = (Link<E>*)ptr;
    }
};

    template <typename E>
        Link<E>* Link<E>::freelist = NULL;

And the class TwoWayList is inherted from the ADT class List. And I'm sure the problem has nothing to do with ADT.

And here is the declaration of class TwoWayList, I just pick some segment which I think might be responsible for the problem.

template <typename E> class TwoWayList :public List<E> {
private:
    Link <E>* head;
    Link <E>* tail;
    Link <E>* curr;
    int cnt;

    void init(){
        curr=tail=head=new Link<E>;
        cnt=0;
    }

    void removeall(){
        while(head!=NULL){
            curr=head;
            head=head->next;
            delete curr;
        }
    }
public:
   void append(const E& it) {
        tail->prev = tail->prev->next = new Link<E>(it, tail->prev, tail);
        cnt++;
    }

and here is the main function

int main(){
    TwoWayList<int> l;
    l.append(1);
    l.append(2);
    l.append(3);
    l.append(4);
    l.append(5);

}

whenever I run this sentence tail->prev = tail->prev->next = new Link<E>(it, tail->prev, tail); , a window will come out and saying Program received signal SIGSEGV, Segmentation fault

Yuan
  • 23
  • 4

1 Answers1

1

Your constructor should be the same names as the class, not init(), which will then correctly set the pointers so the sigfault does not occur.

Likewise you will need to deallocate everything in a deconstructor to prevent memory leaks.

lostbard
  • 5,065
  • 1
  • 15
  • 17