Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Crash when deleting a pointer

I have an assignment to create a PriorityQueue structure and I'm having trouble with this piece of code. When I compile it on my compilator everything's fine, but I tried submitting it to ideone and I get the following error:

"glibc detected *** ./prog: double free or corruption".

I was able to track the part that was giving me this error and I found out that what causes the crash is me trying to delete a pointer at the destructor of my class. The problem is that I don't know why I cant delete it. I don't know a lot about pointers but I thought that if I used new to allocate memory I had to delete it after using it and I think this is what I'm trying to do. Here is my code:

struct PriorityQueue
{
LinkedList queue; LinkNode *it,*node;
int sz;

PriorityQueue(){
    sz=0;
    queue.head=NULL;
    queue.tail=NULL;
    it = NULL;
    node=NULL;
}

~PriorityQueue(){

    if(node != NULL) //this is causing the error.
    delete [] node;


    if(it != NULL)
    delete [] it;
}


int size(){

    return sz;
}


void enqueue(int x){

    node = new LinkNode(x,NULL,NULL);

    if(sz==0){

        queue.insert_head(x);
        sz++;

    }

    else{

    if(x <= queue.head->value ){

        queue.insert_head(x);
        sz++;

    }

    else if( x>= queue.tail->value ){

        queue.insert_tail(x);
        sz++;

    }
    else{

        it = queue.head;


        for(int k=0;k<sz;k++){

                if( (x>= it->value)  && (x <= it->next->value) ){

                     node->next= it->next;
                     node->previous = it;

                     it->next->previous = node;
                     it->next = node;
                     sz++;
                     break;

                }

                    it=it->next;

        }

    }


    }

}

int dequeue_min(){

    int min = queue.remove_head();
    sz--;


    return min;
}

int dequeue_max(){

    int max= queue.remove_tail();
    sz--;

    return max;
}


};



int main()
{
PriorityQueue pq;
pq.enqueue(4);
pq.enqueue(2);
pq.enqueue(7);
pq.enqueue(-6);
pq.enqueue(0);
cout << pq.dequeue_min() << endl;   // debe imprimir -6
cout << pq.dequeue_min() << endl;   // debe imprimir 0
pq.enqueue(3);
cout << pq.dequeue_min() << endl;   // debe imprimir 2
cout << pq.dequeue_min() << endl;   // debe imprimir 3

return 0;
}

Thanks.

like image 223
slugo Avatar asked Mar 07 '26 22:03

slugo


2 Answers

it and node point to objects, not arrays.
You cannot use the array form of delete[] on them.

like image 113
SLaks Avatar answered Mar 10 '26 13:03

SLaks


Using delete[] will try to remove a pointer whose object is an array of some sort. There is another type of delete, that allows for the deletion of pointers to single objects. (Hint: it's pretty intuitive)

like image 45
Baelix Avatar answered Mar 10 '26 11:03

Baelix