开发者

C++ dynamic array assignment error heap[0]=heap[length-1] Error

i am implementing a minmax heap with c++ in netbeans, but i get a strange error. Somebody help, thanks! the statement heap[0]=heap[length-1]; get an segment error, but i can access both the element at 0 and (length-1).

int MinMaxHeap::deleteMin(){
assert(length>0);
int min= heap[0];
heap[0]=heap[length-1];
length--;

int id=0,gid=4*id+3;
while(gid<length){
    int i,cmin=heap[gid],cmin_idx=gid;
    for(i=0;i<4;i++){
        if(gid>(length-1))
            break;
        if(heap[gid]<cmin){
            cmin=heap[gid];
            cmin_idx=gid;
        }
        gid++;
    }开发者_运维知识库
    swap(heap[id],heap[cmin_idx]);
    id=cmin_idx;
    gid=4*id+3;
}
int sid1=2*id+1,sid2=sid1+1,cmin,cmin_idx;
if(sid1<length){
    cmin=heap[sid1];
    cmin_idx=sid1;
    if(sid2<length){
        if(heap[sid2]<heap[sid1]){
            cmin=heap[sid2];
            cmin_idx=sid2;
        }
    }
    if(heap[id]>cmin)
        swap(heap[id],heap[cmin_idx]);
}

return min;

}

the class declaration is:

class MinMaxHeap {

public:

    MinMaxHeap(int size);

    virtual ~MinMaxHeap();

    int findMin();
    int findMax();
    int deleteMin();
    int deleteMax();
    bool insert(int x);
private:

    int getLevel(int i); //get the level of the ith element

    void swap(int&,int&);
    int length;  //current no. of elements of heap
    int size;    //heap size
    int *heap;   //the heap array
};


It's likely that the destructor for the class is being called sometime before the call to deleteMin. Do you ever pass the instance of MinMaxHeap by value? That would trigger the destructor and, assuming you delete heap in the destructor, the heap would be invalid.


MinMaxHeap contains a pointer member, but has no copy constructor。 In case, when copy constructor is needed, MinMaxHeap will invoke default copy constructor and pointer are value copied. When any one of copy of a instance was destroyed, all copy become invalid.

Some examples of copy constructor are invoked as below:

1. void fun(MinMaxHeap m); 
2. std::vector<MinMaxHeap> vecM; //containers
   vecM.push_back(MinMaxHeap(5));
3. MinMaxHeap A(5);
   MinMaxHeap aliasA = A;

Usually, you invoke copy constructor unintentionally. So check your code carefully or implement a copy constructor and try again.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜