为什么我的代码中出现双重免费或损坏错误?

时间:2017-02-09 19:59:04

标签: c++ linked-list corruption double-free

我一直在编写一组整数ADT的链表实现,并且在编译和运行我的代码时遇到了双重释放或损坏错误,并且在我的生活中我无法弄清楚源代码。我原本以为它是在析构函数中但是在我修改它之后看起来似乎不是问题。我正在附上我的代码以供审核。

class list_intset: public intset {

    struct node {
        int number;
        node *next;
        node(int n, node * n2 = NULL):number(n),next(n2){}
    };
    mutable node * head;
    int set_size;

    list_intset(const list_intset & a) { //copy constructor thing
        throw std::domain_error("No copy constructor ");
    }
    list_intset & operator =(const list_intset & a){ //= sign operator
        throw std::domain_error("No = for intset");
    }
//  
public:
    list_intset(){ //default constructor that constructs the empty set
        set_size = 0;
        head = NULL;
    }; 
    virtual ~list_intset(){ //virtual devastator
        node * temp;
        while(head != NULL){
            temp = head->next;
            delete head;
            head = temp;
        }
    }; 

//  //basic operations
    void add(int a){ //add an item to the set
        head = new node(a, head);
        ++set_size;
    }
//  
    void remove(int a){ //removes an item from the set //ask professor about this one, I'm not so sure
        node * temp;
        node * ptr = head;
        while(ptr && ptr->number != a){
            ptr = ptr->next;
        }
        if(ptr != NULL){
            temp = ptr;
            ptr = ptr->next;
            cout << "deleting temp in remove."<<endl;
            delete temp;
        }
    }
    void do_clear(node * n){
        if(n != NULL){
            do_clear(n->next);
            cout << "deleting n in do_clear."<<endl;
            delete n;
        }
    }
    void clear(){ //removes all elements from the set
        do_clear(head);
        set_size = 0;
    }
//  
    bool contains(int a) const{ //returns true if an element is in the set, returns false if it is not.
        node * temp_head = head;
        bool flag = false;
        while(temp_head != NULL){

            if(temp_head->number == a){
                flag = true;
                break;
            }else{
                temp_head = temp_head->next;
            }
        }
        return flag;
    }
    int size() const{ //returns how many elements are in the set
        cout << "size" << endl;
        return set_size;
    }
    void display(std::ostream & a) const{ //displays all of the elements in a set with the curly brackets, ex: {2 3 4 7 9}
        node * temp = head;
        cout << "display" << endl;
        a << "{";
        for(int i = 0; i < set_size; i++){
            a << temp->number << " ";
            temp = temp->next;
        }
        a << "}";
    }

我省略了我写过的设置操作函数,因为我没有在这些函数中删除任何内容。另外,cout语句例如“删除临时删除”我试图在运行和编译期间尝试跟踪错误。

谢谢, 大卫

0 个答案:

没有答案